如何让uitableViewCell同时处理tap和long Press?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何让uitableViewCell同时处理tap和long Press?相关的知识,希望对你有一定的参考价值。
我把它放在cellForRowAtIndexPath中
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(CalorieCountViewController.handleLongPress))
cell.addGestureRecognizer(longPress)
longPress.cancelsTouchesInView = true
let tapPress = UITapGestureRecognizer(target: self, action: #selector(CalorieCountViewController.handleTapPress))
cell.addGestureRecognizer(tapPress)
tapPress.cancelsTouchesInView = true
并将这些(下面的代码)放在它之外,并完全删除didSelectRowAtIndexPath函数,改为使用indexPathForSelectedRow来获取刚刚选择的行用户。
func handleLongPress(sender: UILongPressGestureRecognizer){
let index = tableView.indexPathForSelectedRow!
doSomething(index)
}
func handleTapPress(sender: UITapGestureRecognizer){
let index = tableView.indexPathForSelectedRow!
doSomethingElse(index)
}
原来indexPathForSelectedRow返回nil,但我选择了一行,并且在我的代码中没有“deselectRowAtIndexPath”。
答案
不要将UILongPressGestureRecognizer
添加到Cell
。将其添加到UITableView
的viewDidLoad
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(CalorieCountViewController.handleLongPress))
yourTableView.addGestureRecognizer(longPress)
获取触摸的细胞索引
func handleLongPress(sender: UILongPressGestureRecognizer){
if longPressGestureRecognizer.state == UIGestureRecognizerState.Began {
let touchPoint = longPressGestureRecognizer.locationInView(yourTableView)
if let indexPath = yourTableView.indexPathForRowAtPoint(touchPoint) {
// your code here, get the row for the indexPath or do whatever you want
}
}
}
而不是UITapGestureRecognizer
使用didSelectRowAtIndexPath
是一个更好的方法
另一答案
更新Swift4:
在viewController类的viewDidLoad
中添加这些行(在此示例中,类的名称为YourViewController
)
override func viewDidLoad() {
super.viewDidLoad()
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPress(longPressGestureRecognizer:)))
self.view.addGestureRecognizer(longPressRecognizer)
}
现在在viewController类中添加这个func
@objc func longPress(longPressGestureRecognizer: UILongPressGestureRecognizer) {
if longPressGestureRecognizer.state == UIGestureRecognizerState.began {
let touchPoint = longPressGestureRecognizer.location(in: self.view)
if let indexPath = tableView.indexPathForRow(at: touchPoint) {
// add your code here
// you can use 'indexPath' to find out which row is selected
}
}
}
以上是关于如何让uitableViewCell同时处理tap和long Press?的主要内容,如果未能解决你的问题,请参考以下文章
无法点击 UITableViewCell 上 CustomCell 的 Tap Recognizer
你可以使用 Jenkins Pipeline 解析 TAP 格式吗?
iOS开发中didSelectRowAtIndexPath tap事件响应延迟