How to add a binding gesture to a UICollectionView, while maintaining cell selection?

Task

Add one sign gestures to the UICollectionView ; don't interfere with cell selection.

I want some other taps on the non-element part of the View collection.

The code

Using 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") } 

Result

Yes, now it interferes. When you click on a cell, it records "tapping."

Analysis

  • I check the return value of the hitTest of the collection and cell. Both returned the selected cell, which means that they form a chain of responders Cell → CollectionView
  • no gestures in the cell
  • 3 gestures in the View collection, no one works with cell selection
    • UIScrollViewDelayedTouchesBeganGestureRecognizer
    • UIScrollViewPanGestureRecognizer
    • UITapGestureRecognizer
  • callStack, it seems that the cell selection has a different stack trace with the target gesture action pattern.
  • A double-tap gesture works with cell selection.

Question

Could not find more trace. Any ideas on how cell selection is done or to achieve this?

+7
ios swift uicollectionview uigesturerecognizer uiresponder
source share
2 answers

Whenever you want to add a gesture recognizer, but do not steal strokes from the target view, you must set UIGestureRecognizer.cancelsTouchesInView for your gestureRecognizer instance to false.

+15
source share

Instead of trying to force didSelectItem you can simply get indexPath and / or cell as follows:

 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") } } 
+5
source share

All Articles