infernouk infernouk - 1 month ago 66
Swift Question

Deleting a Row from a UITableView in Swift 3?

Im new to coding and learning swift, I am following a tutorial for swift 2 and working with swift 3 so there are a few issues I have when following along, this being one im proiperly stuck on.

I have a table of names and i am making a swipe and delete function for them which removes them from a names variable which is an array. I selected the functions which most closely resembled the tutorial inside xcode and filled them out, but my app crashes randomly when I click the delete button. Here is my code for the delete button...

Thanks for any help!

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete") { (rowAction: UITableViewRowAction, indexPath: IndexPath) -> Void in

print("Deleted")

self.catNames.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
self.tableView.reloadData()
}

Answer

Use the UITableViewDataSource tableView(:commit:forRowAt:) method in Swift 3.0, see also this answer here:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
  if editingStyle == .delete {
    print("Deleted")

    self.catNames.remove(at: indexPath.row)
    self.tableView.deleteRows(at: [indexPath], with: .automatic)
  }
}
Comments