简体   繁体   中英

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.

 //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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM