F. Bar F. Bar - 1 month ago 9
iOS Question

Add a gestureRecognizer to a tableView cell

I currently have a TableViewController with 3 cells and I'm trying to add a long press gesture recogniser to just print to the logs when detected.

I've added:

class TableTesting: UITableViewController, UIGestureRecognizerDelegate {


and in my
tableView
method I've created a
UILongPressGestureRecognizer
:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Gesture Recognizer Testing"
var lpgr = UILongPressGestureRecognizer(target: self, action: "longPressAction:")
lpgr.minimumPressDuration = 2.0
lpgr.delegate = self
cell.addGestureRecognizer(lpgr)
return cell
}


I've also created the function
longPressAction
:

func longPressAction(gestureRecognizer: UILongPressGestureRecognizer) {
print("Gesture recognized")
}


The issue I'm having is when compiling the code and trying to long press one my cells, the app is crashing and I'm getting this error:


Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[TestingGround.TableTesting
longPressAction:]: unrecognized selector sent to instance
0x7f9afbc055d0'


I'm guessing somehow that the correct information isn't being passed into the function but I'm unsure?

Any help would be appreciated.

Answer

Instead of:

var lpgr = UILongPressGestureRecognizer(target: self, action: "longPressAction:")

Use:

let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(gestureRecognizer:)))