Warm tip: This article is reproduced from stackoverflow.com, please click
ios tableview

How to prevent cells from indenting when using custom swipe actions in edit mode?

发布于 2020-03-27 10:29:22

I'm trying to implement two cells, one that can be deleted by swiping, and one that can't be deleted, but has swipe actions the other way.

This is what it looks like now:

swiping

I don't want the middle cell to be indented when clicking Edit. Without any custom code, all cells would show this red circle and get a delete-button, but I have added a few lines of code to prevent that.

This code will set all cells without a leading or trailing swipe action to not become editable, which explains the bottom cell in the gif. I have to include the leading swipe actions to this, because if the cell isn't editable, then I can't swipe at all.

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    let vm = sections[indexPath.section].viewModels[indexPath.row]
    return vm.leadingSwipeActions != nil || vm.trailingSwipeActions != nil
}

The following code will prevent the middle cell from showing the red circle.

func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    return sections[indexPath.section].viewModels[indexPath.row].trailingSwipeActions == nil ? .none : .delete
}

If I don't pass .none for the cell with leading actions, then it would show the red circle AND it would even show a default deletion-swipe. I don't want the ability to delete this row!

How can I prevent the middle cell from indenting, while still retaining the ability to swipe it?

Questioner
Sti
Viewed
93
Zaya 2019-07-08 21:52

This method seems to work! tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614873-tableview?language=objc