简体   繁体   中英

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) 在此处输入图片说明

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:

self.contentView.isUserInteractionEnabled = false

I think the cell selection was hijacking the touch event.

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
}

Double-check the structure of the XIB file. I lost time dealing with this issue (where the button in the XIB did not seem to respond), as the structure had a second embedded cell, rather than just one (AboutCell in my case).

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM