BobC
BobC

Reputation: 655

UICollectionView button

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?

Upvotes: 3

Views: 726

Answers (2)

BobC
BobC

Reputation: 655

Damn, it's needed to add following func:

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

Upvotes: 1

Mohammadalijf
Mohammadalijf

Reputation: 1377

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

Upvotes: 0

Related Questions