3

enter image description hereコレクションビューのセルにuibuttonアクションを追加するにはどうすればよいですか?

このコレクションビューには、右上隅にある編集ボタンを含むセルがあります。どのようにしてアクションを実行するのですか?

collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCellcell.editbutton.addTargetを追加しようとしましたが、touchUpInsideイベントは検出されません。

+0

http:// codereview。 stackexchange.com/questions/84615/retrieving-values-from-uitableviewcell/84655 –

答えて

5

はyou-が

書き込みのためcellForItemAtIndexPath

スウィフト2.Xでこのコード入用かもしれませ

let editButton = UIButton(frame: CGRectMake(0, 20, 40,40)) 
     editButton.setImage(UIImage(named: "editButton.png"), forState: UIControlState.Normal) 
     editButton.addTarget(self, action: #selector(editButtonTapped), forControlEvents: UIControlEvents.TouchUpInside) 

cell.addSubview(editButton) 

スウィフト3.X

let editButton = UIButton(frame: CGRect(x:0, y:20, width:40,height:40)) 
     editButton.setImage(UIImage(named: "editButton.png"), for: UIControlState.normal) 
     editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControlEvents.touchUpInside) 

     cell.addSubview(editButton) 

そして、あなたのアクション(Action)を行う

override func viewDidLoad() { 

     super.viewDidLoad() 

} 

@IBAction func editButtonTapped() -> Void { 
    print("Hello Edit Button") 
} 
+1

どこでIBActionを記述すればいいですか?CollectionViewCellクラスまたはCollectionViewControllerに書き込むべきですか? –

+0

更新を確認してください – iDeveloper

+0

うごきのように動作します –

8

はuserInteractionがボタンのためだけでなく、UICollectionViewCellのために有効であることを確認してください

func collectionView(_ collectionView: UICollectionView, 
        cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    cell.button.tag = indexPath.row 
    cell.button.addTarget(self, 
     action: #selector(self.yourFunc(), 
     for: .touchUpInside) 
} 

func yourFunc(sender : UIButton){ 
    print(sender.tag) 
} 

で書き、UICollectionViewCellであなたのUIButtonの出口を作成します。

+0

スウィフトにはJavaのようなリスナーがクリックされた方が良いでしょう。このすべては松葉杖のようです。 – user25

1

UICollectionViewのセルのテイクボタン(プログラムまたはストーリーボードを使用)。そのボタンのアクションをセルクラスファイルに追加し、そのセルクラスファイルにデリゲートを宣言し、ボタンアクションメソッドで同じデリゲートを呼び出して編集アクションを実行します。

は、その後、あなたがコレクションビューを作成している中でのViewControllerで同じデリゲートを実装

0

プロトコルCollectionViewCellDelegte { FUNCのcollectionViewCellDelegte(didClickButtonAtインデックス:INT) }

クラスImageCollectionViewCell:UICollectionViewCell {

var index = 0 
var delegte: CollectionViewCellDelegte? = nil 

@IBAction func buttonAction(_ sender: UIButton) { 
    if let del = self.delegte { 
     del.collectionViewCellDelegte(didClickButtonAt: index) 
    } 
} 

}

+0

コードをインデントして何を説明してくださいありますか? https://stackoverflow.com/help/how-to-answer – Nope

関連する問題