I am trying to disable swipe to delete action for some particular cells in tableview. but i could not be find a good solution in swift. I don't want that left side minus sign on cell when overriding "tableView.isEditing = true" method.Here is my code. below code is not disabling swipe to the cell with statusId "12". Hope you understand my problem.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! TableViewDateCell
cell.titleStatus.text = mainList[indexPath.row].statusName
//tableView.isEditing = true
//disable swipe to delete for cell with statusId == "12"
if mainList[indexPath.row].statusId == "12" {
//tableView.isEditing = false
cell.selectionStyle = UITableViewCellSelectionStyle.gray
cell.isUserInteractionEnabled = false
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
}
You might customize the UITableViewDelegate
's function editingStyleForRowAt
, especially returning UITableViewCellEditingStyle.none
when you don't need the swipe, something like:
public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle
{
if mainList[indexPath.row].statusId == "12" {
return UITableViewCellEditingStyle.none
} else {
return UITableViewCellEditingStyle.delete
}
}
Thanks for posting this question and the answers above.
On an expansion of the answers, I had a default row that should never be deleted, so I set a tag on that particular cell and then at first used this method.
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if tableView.cellForRow(at: indexPath)?.tag == 100 {
return false
}
return true
}
HOWEVER - This caused the following warning in Debugger -
Attempted to call -cellForRowAtIndexPath: on the table view while it was in the process of updating its visible cells, which is not allowed.
So, as other commentators have said, use this method below:
Swift 5.0
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if tableView.cellForRow(at: indexPath)?.tag == 100 {
return UITableViewCell.EditingStyle.none
} else {
return UITableViewCell.EditingStyle.delete
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With