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

jch*_*nxu 19 uiresponder uigesturerecognizer ios uicollectionview swift

任务

添加单击手势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")
}
Run Code Online (Sandbox Code Playgroud)

结果

是的,它现在阻碍了它.当您点击单元格时,它会记录"轻拍".

分析

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

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

Jos*_*ann 27

每当您想要添加手势识别器,但不想从目标视图中窃取触摸时,您应该将实例设置UIGestureRecognizer.cancelsTouchesInViewgestureRecognizerfalse.


Fra*_*kie 11

而不是试图强迫didSelectItem你可以这样获取indexPath和/或单元格:

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")
    }
}
Run Code Online (Sandbox Code Playgroud)