我有一个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 并期望他们以某种方式行事。
如果你真的坚持这样做,你可以做的是:
- 在单元格上将 userInteractionEnabled 设置为 false。
- 触摸时,使用indexPathForItemAtPoint检查您是否触摸了单元格:(该点是触摸的位置)
- 在修饰时,使用indexPathforItemAtPoint 来查看您是否位于同一单元格中。然后,您可以手动处理“选择单元格”
- 然后用触摸来做任何其他事情。
基本上,关闭 userInteractionEnabled,然后自己处理单元格选择。
关于ios - 检测 UICollectionView 上的所有触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59884701/