0

I'm building a table view and I cannot seem to get both regular taps and long presses to work.

I have placed this code in my viewDidLoad:

let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
myTableView.addGestureRecognizer(longPress)

and this code is my gesture recognizer:

@objc func handleLongPress(sender: UILongPressGestureRecognizer){
    if UILongPressGestureRecognizer.state == UIGestureRecognizer.State.began {

        let touchPoint = UILongPressGestureRecognizer.location(in: self.myTableView)
        if let indexPath = self.myTableView.indexPathForRowAtPoint(touchPoint) {
            print(indexPath.row)
        }
    }
}

I have found this code here on Stack Overflow, but I do not think it is up to date for Swift 4 because I can not even run it without the build failing.

shim
  • 9,289
  • 12
  • 69
  • 108
Frank Doe
  • 192
  • 1
  • 3
  • 17

1 Answers1

2

UILongPressGestureRecognizer.state should be sender.state and UILongPressGesutreRecognizer.location should be sender.location. Also, the signature for indexPathForRowAtPoint() has been updated to indexPathForRow(at:).

Corrrected code:

@objc func handleLongPress(sender: UILongPressGestureRecognizer) {
    if sender.state == .began {
        let touchPoint = sender.location(in: self.myTableView)
        if let indexPath = self.myTableView.indexPathForRow(at:touchPoint) {
            print(indexPath.row)
        }
    }
}

UILongPressGestureRecognizer is a class name, you need to be calling the class instance.

shim
  • 9,289
  • 12
  • 69
  • 108
  • the syntax have changed a bit for Swift 4 `func indexPathForRow(at point: CGPoint) -> IndexPath?` so `if let indexPath = myTableView.indexPathForRow(at: touchPoint) {` – Leo Dabus Dec 13 '18 at 19:26