UILongPressGestureRecognizer not calling its targe

2020-05-09 03:04发布

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.

1条回答
Explosion°爆炸
2楼-- · 2020-05-09 03:34
//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)
查看更多
登录 后发表回答