How to make tableViewCell handle both tap and longPress?
Based on Bala Answer here is on swift 4 or 5
override func viewDidLoad() {
super.viewDidLoad()
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longpress))
tableView.addGestureRecognizer(longPress)
}
Here is the method
@objc func longPress(sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizer.State.began {
let touchPoint = sender.location(in: tableView)
if let indexPath = tableView.indexPathForRow(at: touchPoint) {
// your code here, get the row for the indexPath or do whatever you want
print("Long press Pressed:)")
}
}
}
Don't add the UILongPressGestureRecognizer
to Cell
. Add it to UITableView
in viewDidLoad
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(sender:)))
tableView.addGestureRecognizer(longPress)
Get the touched cell index by
@objc private func handleLongPress(sender: UILongPressGestureRecognizer) {
if sender.state == .began {
let touchPoint = sender.location(in: tableView)
if let indexPath = tableView.indexPathForRow(at: touchPoint) {
// your code here, get the row for the indexPath or do whatever you want
}
}
}
Instead of UITapGestureRecognizer
use didSelectRowAtIndexPath
is a better way
Update Swift4:
Add these lines in viewDidLoad
of your viewController class (in this example class's name is YourViewController
)
override func viewDidLoad() {
super.viewDidLoad()
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPress(longPressGestureRecognizer:)))
self.view.addGestureRecognizer(longPressRecognizer)
}
Now add this func
in your viewController class
@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
}
}
}