【发布时间】:2017-01-26 21:17:30
【问题描述】:
我一直在尝试在我的 uitableview 上设置长按手势识别器。我已经能够让它注册,但是它似乎给了我相关行的错误信息。我的表格视图通过正常点击按预期工作,它通过了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)
【问题讨论】:
-
也许你应该使用 tableView 而控制器主视图(如果控制器是 UITableViewController 将无法解决问题):
longPressGestureRecognizer.location(in: self.tableView)而longPressGestureRecognizer.location(in: self.view) -
您应该尝试将此代码放在 uitableviewcell 中,然后您应该为此委托。
-
谢谢,完全有道理
标签: ios swift uigesturerecognizer