在 Table 视图中同时使用点击手势和长按
Using tap gesture and long press at the same time in Table View
我正在构建一个 table 视图,但我似乎无法同时正常点击和长按。
我已将此代码放入我的 viewDidLoad:
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
myTableView.addGestureRecognizer(longPress)
此代码是我的手势识别器:
@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)
}
}
}
我在 Stack Overflow 上找到了这段代码,但我认为它不是 Swift 4 的最新代码,因为如果构建失败,我什至无法 运行 它。
UILongPressGestureRecognizer.state
应该是 sender.state
而 UILongPressGesutreRecognizer.location
应该是 sender.location
。此外,indexPathForRowAtPoint()
的签名已更新为 indexPathForRow(at:)
。
更正后的代码:
@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
是一个 class 名称,您需要调用 class 实例。
我正在构建一个 table 视图,但我似乎无法同时正常点击和长按。
我已将此代码放入我的 viewDidLoad:
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
myTableView.addGestureRecognizer(longPress)
此代码是我的手势识别器:
@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)
}
}
}
我在 Stack Overflow 上找到了这段代码,但我认为它不是 Swift 4 的最新代码,因为如果构建失败,我什至无法 运行 它。
UILongPressGestureRecognizer.state
应该是 sender.state
而 UILongPressGesutreRecognizer.location
应该是 sender.location
。此外,indexPathForRowAtPoint()
的签名已更新为 indexPathForRow(at:)
。
更正后的代码:
@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
是一个 class 名称,您需要调用 class 实例。