1

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.

RanLearns
  • 4,086
  • 5
  • 44
  • 81

1 Answers1

3
//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)
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • This was the correct reason for the issue I was facing, although my solution was a bit different because I still need to declare longPressGesture as an instance property so I can add/remove it later on as needed. So still creating it as an instance property buy I am now defining its target elsewhere in the code when self is able to be accessed. Thanks for your help here! – RanLearns Oct 16 '18 at 22:01
  • Exactly right. It doesn't matter when you set the target as long as you don't do it as part of the instance property default initializer! – matt Oct 16 '18 at 22:02