iosswiftuitableviewuicontextualaction

Swift UISwipeActionsConfiguration and segue


I added leadingSwipeAction "Edit" button. However, when i press "Edit" button in simulator, app crashes and shows "Thread 1: signal SIGBART" in **prepare(for:sender:)**method.

I saw similar questions, but their solutions did't help. I'm newbie and can't understand where is the problem.

`//my edit button code`
   override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        
        let edit = UIContextualAction(style: .normal, title: "Edit") { [self] (contextualAction, view, actionPrformed: (Bool) -> Void) in
            
            //TODO:
            
            performSegue(withIdentifier: "EditItem", sender: self)
            actionPrformed(true)
        }
        
            return UISwipeActionsConfiguration(actions: [edit])
        }

// segue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        if segue.identifier == "AddItem" {
            let controller = segue.destination as! AddAndEditItemViewController
            controller.delegate = self
                    }
       
        else if segue.identifier == "EditItem" {
            let controller = segue.destination as! AddAndEditItemViewController
            controller.delegate = self
        
        if let indexPath = tableView.indexPath(
                  for: sender as! UITableViewCell) { //erorr shows here
                  controller.itemToEdit = items[indexPath.row]
                }                                           
    }

}


Solution

  • self here

    performSegue(withIdentifier: "EditItem", sender: self)
    

    is the vc instance itself not the cell , you need to pass indexPath.row

    performSegue(withIdentifier: "EditItem", sender: indexPath.row)
    

    Then

    let index = sender as! Int
    controller.itemToEdit = items[index] 
    

    You can also use

    guard let index = tableView.indexPathForSelectedRow?.row else { return }