繁体   English   中英

CollectionView 中的按钮不可点击

[英]Button inside CollectionView not clickable

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

这是我的收藏布局(我隐藏了一些敏感数据) 在此处输入图片说明

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

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 中的集合视图函数:

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 答案的评论中的解决方案: https : //stackoverflow.com/a/44908916/406322

我需要在 MyCollectionViewCell 中添加这个:

self.contentView.isUserInteractionEnabled = false

我认为细胞选择正在劫持触摸事件。

我面临同样的问题,并在花了很多时间后找到了最佳解决方案。

cell.contentView.isUserInteractionEnabled = false

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

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

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

     cell.contentView.isUserInteractionEnabled = false
     return cell
}

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

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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