CollectionView 中的按钮不可点击 [英] Button inside CollectionView not clickable

查看:53
本文介绍了CollectionView 中的按钮不可点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

I have a xib file where a Touch Up Inside event of a button has been hooked up to the connectButton IBAction.

在我的 ViewController 中:

And in my ViewController:

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

这是我的 ViewController 中的集合视图函数:

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

}

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

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?

推荐答案

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

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

我需要在 MyCollectionViewCell 中添加这个:

I needed to add this in MyCollectionViewCell:

self.contentView.isUserInteractionEnabled = false

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

I think the cell selection was hijacking the touch event.

这篇关于CollectionView 中的按钮不可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆