【问题标题】:Buttons in a UICollectionView don't receive touch eventsUICollectionView 中的按钮不接收触摸事件
【发布时间】:2017-11-01 04:49:07
【问题描述】:

我已经环顾了一段时间,但似乎无法弄清楚如何阻止集合视图单元格消耗触摸事件。

我需要将触摸事件传递到相应的单元格中,以便可以按下单元格内的按钮。我在想我可能需要弄清楚如何禁用 UICollectionView 的 didSelectCellAtIndexFunction?

我也认为这是一个潜在的解决方案:collectionView.cancelsTouchesInView = false

此链接也可以帮助某人回答我的问题:How to add tap gesture to UICollectionView , while maintaining cell selection?

提前致谢!

编辑:

我还应该补充一点:我的按钮被添加到一个视图中,该视图又被添加到单元格的 contentView 中。我的代码都是以编程方式完成的,所以我根本没有使用 interface Builder。

【问题讨论】:

  • 确保您的按钮的用户交互已启用,并且它没有被任何其他视图或某些透明对象覆盖!
  • 检查按钮是否不在collectionViewCell的范围内
  • 按钮在单元格的范围内@mkowal87
  • 你不需要做任何特别的事情来获得一个按钮来注册一个集合视图单元格中的点击。您需要显示用于创建按钮并将它们添加到单元格的代码。

标签: ios swift uibutton uicollectionview uicollectionviewcell


【解决方案1】:

试试你的手机。

self.contentView.isUserInteractionEnabled = false

【讨论】:

    【解决方案2】:
    func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
            return false // all cell items you do not want to be selectable
        }
    

    假设所有按钮都连接到同一个选择器,您需要一种方法来区分单击了哪个单元格的按钮。找出按钮单元格索引的方法之一是:

    func buttonPressed(button: UIButton) {
        let touchPoint = collectionView.convertPoint(.zero, fromView: button)
        if let indexPath = collectionView.indexPathForItemAtPoint(touchPoint) {
            // now you know indexPath. You can get data or cell from here.
        }
    }
    

    【讨论】:

    • 感谢 Joseph,但我没有使用 NIB,我的 collectionView、单元格和按钮都是以编程方式制作的,而且我的视图肯定会添加到 contentView
    • 然后尝试覆盖 UICollectionViewDelegate 的 collectionView(:shouldSelectItemAt:) 方法,并在您不希望调用 collectionView(:didSelectItemAt:) 的项目上返回 false。跨度>
    猜你喜欢
    • 2015-11-07
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多