如何让tableViewCell同时处理tap和longPress?

我把它放在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来获取刚刚select的行用户。

 func handleLongPress(sender: UILongPressGestureRecognizer){ let index = tableView.indexPathForSelectedRow! doSomething(index) } func handleTapPress(sender: UITapGestureRecognizer){ let index = tableView.indexPathForSelectedRow! doSomethingElse(index) } 

结果indexPathForSelectedRow返回nil,但我没有select一行,并且在我的代码中没有任何“deselectRowAtIndexPath”。

不要将UILongPressGestureRecognizer添加到Cell 。 将它添加到viewDidLoad UITableView

 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 } } } 

使用didSelectRowAtIndexPath是一个更好的方法,而不是UITapGestureRecognizer