CollectionView 内的按钮不可点击

Button inside CollectionView not clickable

我在 collection 视图的自定义单元格中有一个按钮。 collection视图在滚动视图上。出于某种原因,我无法点击按钮。我已检查我的所有元素是否都启用了用户交互。

这是我的 collection 布局(我隐藏了一些敏感数据)

这是我的自定义 collection 视图单元格:

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

我有一个 xib 文件,其中按钮的 Touch Up Inside 事件已连接到 connectButton IBAction。

在我的 ViewController 中:

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

这是我 ViewController 中的 collection 视图函数:

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

}

单击按钮时没有任何反应。我在这里错过了什么吗?滚动视图是否干扰?我需要指定一个 addTarget 吗?或者别的什么?

在搜索整个网络后,我终于找到了这个 SO 答案的评论中的解决方案:

我需要在 MyCollectionViewCell 中添加:

self.contentView.isUserInteractionEnabled = false

我认为单元格选择劫持了触摸事件。

仔细检查 XIB 文件的结构。我浪费了时间处理这个问题(XIB 中的按钮似乎没有响应),因为结构有第二个嵌入式单元格,而不是只有一个(在我的例子中是 AboutCell)。

我遇到了同样的问题,花了很多时间找到了最好的解决方案。

cell.contentView.isUserInteractionEnabled = false

但它是完美的解决方案,并且只在单元格中为项目方法添加一行

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

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

     cell.contentView.isUserInteractionEnabled = false
     return cell
}