How to add swipe actions for table view cell in swift 5

3.2k Views Asked by At

I want to add Edit action to display when the user swipes a table row. I used to be able to use the tableView(_:editActionsForRowAt:) method, but it is now deprecated. And in the tableView(_:commit:forRowAt:) method, there is no action I need. How can I add actions for my cells?

2

There are 2 best solutions below

1
On BEST ANSWER

Try the following method:

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let item = UIContextualAction(style: .destructive, title: "Delete") {  (contextualAction, view, boolValue) in
            //Write your code in here
        }
        item.image = UIImage(named: "deleteIcon")

        let swipeActions = UISwipeActionsConfiguration(actions: [item])
    
        return swipeActions
    }
1
On
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in
        // delete item at indexPath
    }

    let share = UITableViewRowAction(style: .normal, title: "Disable") { (action, indexPath) in
        // share item at indexPath
    }

    share.backgroundColor = UIColor.blue

    return [delete, share]
}

Note that the first button uses a .destructive style so it will be colored red by default, but the second button specifically has a blue color assigned to it.