Search code examples
iosswiftuicollectionviewuipangesturerecognizer

didSelectItemAt not called when using UIPanGestureRecognizer in View


I am using both a tap and pan gesture in my View. The view has a UICollectionView where I am trying to call didSelectItemAthowever the method is not called.

I have tried the following, but with no luck.

override func viewDidLoad() {
   panGesture.delegate = self
   tapGesture.delegate = self
}

extension AddNotebookViewController: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}

Does anybody have any idea what the issue may be ?


Solution

  • The problem, as you've already guessed, is that the background view's gesture recognizer swallows the tap that would select the collection view cell. To solve the problem, implement this gesture recognizer delegate method in your view controller:

    func gestureRecognizerShouldBegin(_ gr: UIGestureRecognizer) -> Bool {
        let p = gr.location(in: self.view)
        let v = self.view.hitTest(p, with: nil)
        return v == gr.view
    }
    

    The result is that if the gesture is in the collection view, the background view's gesture recognizer won't begin and normal selection will be able to take place.