Reputation: 155
Normally when this function is called, deleting a table view cell by swiping left is allowed:
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
dataSource.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
}
}
But I created an edit button like this:
self.navigationItem.leftBarButtonItem = self.editButtonItem
and I'd like to enable deleting a cell only when the edit button was clicked and NOT just by swiping. Is this possible?
Upvotes: 0
Views: 833
Reputation: 155
I solved it this way:
var editMode = false
...
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if editMode == true {
return true
} else {
return false
}
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
if(editing) {
tableView.reloadData()
editMode = true
}
else if(!editing) {
tableView.reloadData()
editMode = false
}
}
Upvotes: 0
Reputation: 72420
Create one Boolean
instance property with default value false
and set it to true
on the action of your BarButttonItem
after that use that boolean property in canEditRowAt
method to allow/disallow row edit.
var allowEdit = false
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return allowEdit
}
Note: Don't forgot it to set false
again once your delete is complete.
Upvotes: 2