在 UITableView 上长按手势

Long press gesture on UITableView

我一直在尝试在我的 uitableview 上设置长按手势识别器。我已经能够让它注册,但它似乎为我提供了相关行的错误信息。我的 tableview 通过正常单击按预期工作,它通过了 indexPath.row 并且我能够从与该行关联的 people 数组中获取正确的记录。但是在使用下面的代码时,indexPath.row 似乎不一致并选择上下行,然后在滚动时它会在长按时选择随机记录。

func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {

    if longPressGestureRecognizer.state == UIGestureRecognizerState.began {

        let touchPoint = longPressGestureRecognizer.location(in: self.view)
        if let indexPath = tableView.indexPathForRow(at: touchPoint) {
            let person = people[indexPath.row]
            print("\(person.name)")
            ///////works but erratic responses//////////
        }
    }
}

//// in view did load i have this


    let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(PeopleVC.longPress(_:)))
    longPressGesture.minimumPressDuration = 1.0 // 1 second press
    longPressGesture.delegate = self
    self.tableView.addGestureRecognizer(longPressGesture)

改变这个:

let touchPoint = longPressGestureRecognizer.location(in: self.view)

为此:

let touchPoint = longPressGestureRecognizer.location(in: self.tableView)

您正在寻找 UITableView 内部的手势,而不是 UIView