I'm sorry if this looks like a duplicate, I saw similar questions in here, I just couldn't get their answers to work:
I have a tableView with a list of user-created realmObjects. My current delete-function looks like this (and works just fine):
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let realm = try! Realm()
try! realm.write {
realm.delete(allDiaries[indexPath.row])
}
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
My problem is that I wan't there to be a 'Are you sure you wan't to delete?'- pop-up with two options in it; "Yes, delete!" & "No thanks."
I can easily create the UIAlertController and get it to display it, when I slide to delete a cell or press the delete-button - but the stupid thing is, that the cell is deleted the very second the delete-button is pressed and only after that, the (complete useless!) UIAlertController pops up - and no matter what you press, it just disappears and the cell is deleted. My current attempt:
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
let alert = UIAlertController(title: "Are you sure you wish to delete diary?", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "No thanks!", style: .cancel)
let action1 = UIAlertAction(title: "Delete!", style: .destructive)// <-- handler: 'deletefunction'
alert.addAction(action)
alert.addAction(action1)
if editingStyle == .delete {
present(alert, animated: true)
let realm = try! Realm()
try! realm.write {
realm.delete(allDiaries[indexPath.row])
}
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
}
So obviously, I wan't to move the 'delete-tableViewCell-method' inside the "Action1"(Delete-button in pop-alert!) and away from the delete-button itself. <-- This should ONLY show the pop-alert!
I'm guessing I should have this 'delete-tableViewCell-method' inside a handler - but I just can't move the method out of this tableView-method to create the handler, without xCode complaining. So how do I create the handler and insert it correctly?
Thanks! :)
do like
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let alert = UIAlertController(title: "Are you sure you wish to delete diary?", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "No thanks!", style: .cancel)
let action1 = UIAlertAction(title: "Delete!", style: .destructive, handler: { _ in
let realm = try! Realm()
try! realm.write {
realm.delete(allDiaries[indexPath.row])
}
tableView.deleteRows(at: [indexPath], with: .fade)
})
alert.addAction(action)
alert.addAction(action1)
present(alert, animated: true)
}
}