ios - 在 UITableView 上长按手势

标签 ios swift uigesturerecognizer

我一直在尝试在我的 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 中寻找手势。

关于ios - 在 UITableView 上长按手势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41883136/

相关文章:

ios - 如何检查 UITextField 中看不见的字符?

ios - 定时器未同步

ios - 如何获取UIPanGesture的起点并不断计算移动距离?

iOS:实现单指平移和两指平移手势?

ios - 指定 NSURLConnection 和 UIWebView 的网络类型

ios - 如何绑定(bind) UIView 的属性

swift - 将数据从 UIViesController 传递到 UIView, Swift ios

iOS Swift PerformSegueWithIdentifier 用于发送数据

objective-c - 需要知道哪些自定义 UIViews 在点击中

ios - 在 iOS 中使用 NSJSONSerialization 是否有数据限制?