3

I'm trying to create UICollectionView with buttons. I can set button titles but target action doesn't work. Below is my code:

    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")
}

Does anybody know what am I doing wrong?

BobC
  • 639
  • 5
  • 19

2 Answers2

1

Damn, it's needed to add following func:

    func collectionView(_ collectionView: UICollectionView, canFocusItemAt indexPath: IndexPath) -> Bool {
    return false
}
BobC
  • 639
  • 5
  • 19
0

you should use delegates to call methods on viewcontrollers.

protocol TVButtonCellDelegate: class {
    func buttonClicked()
}

then create weak variable on TVButtonCell to pass delegate.

weak var delegate: TVButtonCellDelegate?

and also IBAction on tvbuttoncell to call method inside delegate

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

then you simply apply delegate on firstviewcontroller

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

and then assign firstcontroller to cell when you create one

 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
Mohammadalijf
  • 1,387
  • 9
  • 19