Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button inside CollectionView not clickable

I have a button in a custom cell of a collectionview. The collectionview is on a scrollview. For some reason, I am not able to click on the button. I've checked that all my elements have User Interaction enabled.

Here is my layout of the collection (I've hidden some sensitive data) enter image description here

Here is my custom collection view cell:

class MyCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var connectButton: UIButton!

    var onConnectTap: (MyCollectionViewCell) -> Void)?
    @IBAction func connectButton(_ sender: Any) {
        onConnectTap?(self)
    }

    func populate(_ user: User) {
        nameLabel.text = user.name
     }
}

I have a xib file where a Touch Up Inside event of a button has been hooked up to the connectButton IBAction.

And in my ViewController:

MyCollectionView.register(UINib(nibName: "MyCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell") 

Here's my collection view function in my ViewController:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell
        let user = users.values[indexPath.row]
        cell.populate(user)

        cell.onConnectTap = { (cell) in
            //do something
        }

        return cell

}

Nothing happens when I click on the button. Am I missing something here? Is the scroll view interfering? Do I need to specifiy a addTarget? Or something else?

like image 750
Prabhu Avatar asked Apr 02 '18 16:04

Prabhu


2 Answers

After searching the entire web pretty much, I finally found the solution that was in the comment of this SO answer: https://stackoverflow.com/a/44908916/406322

I needed to add this in MyCollectionViewCell:

self.contentView.isUserInteractionEnabled = false

I think the cell selection was hijacking the touch event.

like image 155
Prabhu Avatar answered Sep 20 '22 01:09

Prabhu


I'm facing the same issue and found the best solution after spending much time.

cell.contentView.isUserInteractionEnabled = false

But its the perfect solution, and adds only one line in the cell for item method

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell

     cell.contentView.isUserInteractionEnabled = false
     return cell
}
like image 42
Maulik Patel Avatar answered Sep 19 '22 01:09

Maulik Patel