2016-12-08 5 views
2

ボタンでUICollectionViewを作成しようとしています。ボタンのタイトルは設定できますが、ターゲットのアクションは機能しません。以下は私のコードです:UICollectionViewボタン

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TVButtonCell", for: indexPath) as! TVButtonCell 
    cell.channelButton.setTitle(channelKeys[indexPath.row], for: .normal) 
    cell.channelButton.addTarget(self, action: #selector(FirstViewController.pressed(_:)), for: .primaryActionTriggered) 
    return cell 
} 

    func pressed(_ sender: AnyObject) { 
    print("Button pressed") 
} 

私は間違っていますか?

+0

アプリがクラッシュしていますか?完全なスタックトレースを通過できますか? – nitinsh99

+0

UICollectionViewセルにIBActionsを追加し、ViewControllerに代理人を追加することをお勧めします – Nathaniel

+0

また、おそらくこれが役立ちます:http://stackoverflow.com/questions/29610316/how-to-add-a-delete-button-コレクションビュー - セル - イン - スイフト?rq = 1 – Nathaniel

答えて

0

はくそー、以下のFUNC追加するために必要なの :あなたがボタンを押したときに

func collectionView(_ collectionView: UICollectionView, canFocusItemAt indexPath: IndexPath) -> Bool { 
    return false 
} 
0

デリゲートを使用して、ViewControllerのメソッドを呼び出す必要があります。

protocol TVButtonCellDelegate: class { 
    func buttonClicked() 
} 

次に、代理人を渡すためにTVButtonCellに弱い変数を作成します。 tvbuttoncell上

weak var delegate: TVButtonCellDelegate? 

ともIBActionは、あなたは、単にfirstviewcontroller

extension FirstViewController: TVButtonCellDelegate { 
    func buttonClicked() { 
     print("button clicked") 
    } 
} 

にデリゲートを適用し、その後、作成時にセルにfirstcontroller割り当てる

@IBAction func tvButtonClicked(sender: UIBUtton) { 
    delegate?. buttonClicked() 
} 

その後、デリゲート内のメソッドを呼び出すために1

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TVButtonCell", for: indexPath) as! TVButtonCell 
    cell.channelButton.setTitle(channelKeys[indexPath.row], for: .normal) 
    cell.delegate = self 
    return cell 
関連する問題