Reputation: 407
I am implementing a long press in the uitableview through storyboard in swift3. I have only one prototype cell set in the storyboard. But the problem is the long press is being detected only in the first cell. Rest of the cells are not listening to the long press gesture.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let row = indexPath.row
cell.textLabel?.text = "Label"
return cell
}
@IBAction func longPress(_ guesture: UILongPressGestureRecognizer) {
if guesture.state == UIGestureRecognizerState.began {
print("Long Press")
}
}
The warning shown in the console is:
at a time, this was never allowed, and is now enforced. Beginning with iOS 9.0 it will be put in the first view it is loaded into.
Upvotes: 0
Views: 599
Reputation: 8563
Attach the gesture to the tableview, and when the gesture is triggered figure out which indexPath was selected.
override func viewDidLoad() {
super.viewDidLoad()
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.longPress(_:)))
tableView?.addGestureRecognizer(longPressRecognizer)
}
func longPress(_ guesture: UILongPressGestureRecognizer) {
if guesture.state == UIGestureRecognizerState.began {
let point = guesture.location(in: tableView)
let indexPath = tableView.indexPathForRow(at: point);
print("Long Press \(String(describing: indexPath))")
}
}
Because a tableview is a kind of scrollview it is best to attach the gestures to the tableview itself and not any of its subview. This way it is less likely to interfere with the other gestures that must be tracked.
Upvotes: 4
Reputation: 8322
You need to add gesture for all cell in cellForRowAtIndexPath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let row = indexPath.row
cell.textLabel?.text = "Label"
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(HomeViewController.longPress(_:)))
cell?.addGestureRecognizer(longPressRecognizer)
return cell
}
func longPress(_ guesture: UILongPressGestureRecognizer) {
if guesture.state == UIGestureRecognizerState.began {
print("Long Press")
}
}
Upvotes: 1