Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView disable swipe to delete for particular cells swift

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) {

}
like image 578
John Avatar asked Mar 02 '18 06:03

John


2 Answers

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
    }
}
like image 135
Andrea Mugnaini Avatar answered Oct 02 '22 12:10

Andrea Mugnaini


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
    }
}
like image 30
user3580269 Avatar answered Oct 02 '22 14:10

user3580269