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)
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?
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:
I think the cell selection was hijacking the touch event.