问题
I have swipeable tableview cells. The intention is to let the user swipe rows left or right completely (swipe out completely), and the swiped row gets removed from the table (like how Inbox by Gmail works). Everything works fine, but I had a question.
func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let swipeRightAction = UIContextualAction(style: .destructive, title: "", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
let item = self.myItems[indexPath.row]
self.swipeRight(item) //do something
self.myItems.remove(at: indexPath.row)
success(true)
})
return UISwipeActionsConfiguration(actions: [swipeRightAction])
}
How can I set the threshold/distance (how much the user has to swipe before the action is taken)? Currently, the user has to swipe half way, before the row gets swiped out. Can I change this point so the user only needs to swipe a little (say 20% of the way) to swipe out the row?
回答1:
There is no direct configuration method for it.
Solution
But you can build it yourself:
- add a UIPanGestureRecognizer to the table
- allow simultaneous recognitions of gestures
- when a swipe ends check for direction and compute percentage out of the translation
- determine the affected table row
- delete it
Code
A swipe of the cells to the left by 20%, leading to the deletion of a row, would look like this in the code:
class ViewController: UITableViewController, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
...
let swipeGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(onSwiped(_:)))
swipeGestureRecognizer.delegate = self
self.tableView.addGestureRecognizer(swipeGestureRecognizer)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
@objc private func onSwiped(_ gestureRecognizer: UIPanGestureRecognizer) {
if gestureRecognizer.state == .ended {
let translation = gestureRecognizer.translation(in: self.view)
guard translation.x < 0 else { return }
let width = self.tableView.bounds.width
let percentage = -translation.x / width
print("swiped left percentage:\(percentage)")
if percentage > 0.2 {
let location = gestureRecognizer.location(in: self.tableView)
if let indexPath = self.tableView.indexPathForRow(at: location) {
print("delete row: \(indexPath.row)")
self.dataSource.remove(at: indexPath.row)
self.tableView.reloadData()
}
}
}
}
Demo
来源:https://stackoverflow.com/questions/53265211/how-to-configure-threshold-distance-when-swiping-on-uitableviewcell