【问题标题】:Button inside CollectionView not clickableCollectionView 内的按钮不可点击
【发布时间】:2018-09-11 21:32:25
【问题描述】:

我在 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 吗?还是别的什么?

【问题讨论】:

  • connectButton 也没有被调用吗?您在界面生成器中正确连接了吗?
  • 它没有被调用,是的,我已经仔细检查了它在 IB 中是否正确连接。
  • 创建按钮的委托方法
  • 您应该尝试将您的收藏视图及其父滚动视图的 clipsToBounds 属性设置为true。由于您的集合视图位于滚动视图中,因此滚动视图的大小可能具有挑战性,也许您可​​以看到单元格,但父视图的大小不正确,从而弄乱了响应链。
  • @DirtyHenry 都已经在 IB 中将 Clip To Bounds 设置为 true。

标签: ios swift uicollectionview uicollectionviewcell swift4


【解决方案1】:

在搜索了整个网络之后,我终于找到了这个SO答案评论中的解决方案:https://stackoverflow.com/a/44908916/406322

我需要在 MyCollectionViewCell 中添加这个:

self.contentView.isUserInteractionEnabled = false

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

【讨论】:

  • 在我尝试了一整天 cell.contentView.isUserInteractionEnabled = false 和 public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { print( URL) 返回真 }
  • 哇,这太晦涩难懂了。很棒的发现!
  • 如果此解决方案对您有用,可能是因为在 MyCollectionViewCell 中您没有正确地将按钮添加为contentView 的子视图(或子视图的子视图);您可能会将按钮添加到view。所以解决方案——而不是禁用contentView上的交互,您应该将按钮添加到contentView而不是view。
【解决方案2】:

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

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
}

【讨论】:

  • 请检查您要单击哪个视图或按钮,确保启用或未启用用户交互@Chandni
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    相关资源
    最近更新 更多