ios - 检测 UICollectionView 上的所有触摸

标签 ios swift uicollectionview

我有一个UICollectionView,里面有UICollectionViewCells。当用户触摸 UICollectionView 时,我希望收到通知,直到他们松开手指。我尝试像这样子类化 UICollectionView :

final class MyCollectionView: UICollectionView {
    var hasTouch = false

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        hasTouch = true
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesCancelled(touches, with: event)
        hasTouch = false
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        hasTouch = false
    }
}

但是当有单元格挡住时,这不起作用,因为它们不会将触摸传递到 Collection View 。解决此问题的一种方法是将单元格上的 userInteractionEnabled 设置为 false,但我无法这样做,因为我确实需要将单元格上的 userInteractionEnabled 设置为 true。我该如何解决这个问题?

最佳答案

重新设计交互。你试图用 CollectionView 做两件不兼容的事情,而以这种方式对抗 UIKit 只会导致眼泪。这也违背了用户的期望,他们已经看到了大量的 Collection View 并期望他们以某种方式行事。

如果你真的坚持这样做,你可以做的是:

  1. 在单元格上将 userInteractionEnabled 设置为 false。
  2. 触摸时,使用indexPathForItemAtPoint检查您是否触摸了单元格:(该点是触摸的位置)
  3. 在修饰时,使用indexPathforItemAtPoint 来查看您是否位于同一单元格中。然后,您可以手动处理“选择单元格”
  4. 然后用触摸来做任何其他事情。

基本上,关闭 userInteractionEnabled,然后自己处理单元格选择。

关于ios - 检测 UICollectionView 上的所有触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59884701/

相关文章:

ios - 需要用按钮 Swift 生成的 Int 更改 UIImageView

ios - 带 xpath/css 的 Swift/UIWebView

ios - 使用 iOS 图表将图片保存到相机胶卷

ios - 在大小更改时使 Collection View 布局无效的正确方法

iphone - 如何处理 subview 的方向变化

ios - 当按钮按下主机应用程序时如何更改自定义键盘的背景颜色?

ios - 重新定义目标操作方法以便 `UIButtons` 将消息中继到我的 `UIViewController` 中的方法的最安全方法是什么?

ios - 具有相同背景的多个 ViewController

swift - UITextView 字体总是固定大小

ios - UICollectionView 在保持位置上方插入单元格(如 Messages.app)