Oranutachi
Oranutachi

Reputation: 1279

How to add action when Trailing Swipe Action cancelled (Swift 5)

In my project I use trailingSwipeActionsConfigurationForRowAt func. And I also use selectRow func when I need. If my cell is selected and I use swipe on it and then I cancelled it (swipe from left to right), my cell doesn't selected again. Where can I fix it (use selectRow again)?

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleteAction = UIContextualAction(style: .destructive, title: "") { [weak self] (contextualAction, view, boolValue) in
            guard let self = self else { return }
            self.deleteRow(at: indexPath)
        }
        deleteAction.image = UIImage(systemName: "trash")
        
        let swipeActions = UISwipeActionsConfiguration(actions: [deleteAction])
        
        return swipeActions
    }

Upvotes: 1

Views: 1532

Answers (2)

Caco Cavalcanti
Caco Cavalcanti

Reputation: 87

You can use:

func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
  //Get the cell's indexPath (be aware of the optional argument and threat it the way you want)
  let cell = tableView.cellForRow(at: indexPath!)
  //Use the cell to the changes you need
}

Also you can use an animation if you want to achieve a smooth effect.

Upvotes: 3

NaveedUlHassan5
NaveedUlHassan5

Reputation: 265

you're not calling the completion handler. According to the API documentation it is necessary to call the completion handler to indicate whether the operation was successful.

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
            let deleteAction = UIContextualAction(style: .destructive, title: "") { _, _, complete in
                // remove object from your array..
                self.arrayName.remove(at: indexPath.row)
                //reload the table to avoid index out of bounds crash..
                self.tableView.deleteRows(at: [indexPath], with: .automatic)
                complete(true)
            }
            
            deleteAction.image = UIImage(named: "trash")
            let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
            configuration.performsFirstActionWithFullSwipe = true
            return configuration
 }

Upvotes: 0

Related Questions