Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableViewCell row action while table is editing

I have a UITableView which I need to both reorder and allow for cells to be deleted by swiping left on a cell to reveal the Delete action. Is it possible to have both at the same time?

For the table I have:

tableView.allowsSelectionDuringEditing = true
tableView.isEditing = true

For the datasource:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    // I do nothing here
}

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    // This is where I rearrange my data source array
}

And for the delegate:

func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
    return .none
}
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
    return false
}

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: .destructive, title: "Remove") { action, index in
        // delete row
    }
    delete.backgroundColor = UIColor.appRed

    return [delete]
}

So what I want to have is:

  • Reorder control allowing me to move a cell
  • Swipe left to reveal cell actions

And I need these to be visible and work at the same time. Can this be done?

like image 756
Horea Avatar asked May 13 '26 07:05

Horea


1 Answers

Swipe to delete is not possible when your UITableView is in editing mode.

If you want to hide the delete button on the left when in editing mode you have to implement the following methods:

override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
    return false
}

override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
    return tableView.isEditing ? .none : .delete
}

I think this is the closest you can get.

like image 158
André Slotta Avatar answered May 15 '26 14:05

André Slotta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!