Search code examples
iosdelegatesuigesturerecognizerios12uilongpressgesturerecogni

UILongPressGestureRecognizer not calling its target method


This worked with devices on iOS 11, but with my device updated to iOS 12 it no longer works:

//the viewcontroller is initiated with UIGestureRecognizerDelegate

let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress))

//in cellForRowAt:
longPressGesture.minimumPressDuration = 1.0
longPressGesture.delegate = self
longPressGesture.cancelsTouchesInView = false
cell.addGestureRecognizer(longPressGesture)

@objc func longPress(longPressGestureRecognizer: UILongPressGestureRecognizer) {
     //never called
}

I also tried adding the gesture recognizer to a button in viewDidLoad to ensure it wasn't an issue with the tableview, and the longPress function is still not getting called.


Solution

  • //the viewcontroller is initiated with UIGestureRecognizerDelegate
    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
    

    It looks like you are trying to make longPressGesture an instance property of your UIViewController while giving it a target and action as part of its initializer. That's not going to work, because at the time it is initialized, the target, self, is not the instance. There is no instance yet; the instance is what we are in the middle of creating!

    Instead, move that line into cellForRowAt:, like this:

    //in cellForRowAt:
    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
    longPressGesture.minimumPressDuration = 1.0
    longPressGesture.delegate = self
    longPressGesture.cancelsTouchesInView = false
    cell.addGestureRecognizer(longPressGesture)