如何在保持单元格选择的同时向UICollectionView添加点击手势?

任务

UICollectionView添加单击手势,不要妨碍单元格选择。

我想在collectionView的无单元格部分进行一些其他的点击。

使用XCode8,Swift 3。

 override func viewDidLoad() { ... collectionView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap))) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print(indexPath) } func tap(sender: UITapGestureRecognizer){ print("tapped") } 

结果

是的,它现在阻碍了它。 当您点击单元格时,它会记录“轻敲”。

分析

  • 我检查了collectionView和单元格的hitTest返回值。 两者都返回了tapped单元格,这意味着它们形成了Cell – > CollectionView的响应链
  • 细胞上没有手势
  • 关于collectionView的3个手势,似乎没有人使用单元格选择
    • UIScrollViewDelayedTouchesBeganGestureRecognizer
    • UIScrollViewPanGestureRecognizer
    • UITapGestureRecognizer
  • callStack,似乎单元格选择具有不同的堆栈跟踪与手势的目标 – 动作模式。
  • 双击手势与单元格选择一起使用。

找不到更多的痕迹。 有关如何实施细胞选择或实现此任务的任何想法?

无论何时您想要添加手势识别器,而不是从目标视图中窃取触摸,您都应该将gestureRecognizer实例的UIGestureRecognizer.cancelsTouchesInView设置为false。

您可以通过以下方式获取indexPath和/或单元格,而不是尝试强制使用didSelectItem

 func tap(sender: UITapGestureRecognizer){ if let indexPath = self.collectionView?.indexPathForItem(at: sender.location(in: self.collectionView)) { let cell = self.collectionView?.cellForItem(at: indexPath) print("you can do something with the cell or index path here") } else { print("collection view was tapped") } }