I would like to reuse code to show alert when I delete some row in tableview in a few my view controllers:
func confirmDelete(item: String) {
let alert = UIAlertController(title: "Delete Planet", message: "Are you sure you want to permanently delete (item)?", preferredStyle: .actionSheet)
let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: handleDeleteItem)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: cancelDeleteItem)
alert.addAction(deleteAction)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
}
func handleDeleteItem(alertAction: UIAlertAction!) -> Void {
if let indexPath = deletePlanetIndexPath {
presenter?.removePlanet(atIndex: indexPath, completion: { (result) in
switch result {
case .success(_):
self.tableView.deleteRows(at: [indexPath], with: .fade)
break
case let .failure(error):
print(error)
break
}
})
deletePlanetIndexPath = nil
}
}
func cancelDeleteItem(alertAction: UIAlertAction!) {
deletePlanetIndexPath = nil
}
The only one part will be different everytime:
presenter?.removePlanet(atIndex: indexPath, completion: { (result) in
switch result {
case .success(_):
self.tableView.deleteRows(at: [indexPath], with: .fade)
break
case let .failure(error):
print(error)
break
}
})
So as you can see I can simple do subclassing and declare some closure variable which will be triggered each time deleteAction invoked.
It's very simple way, but I am not super fun of subclassing. Maybe there is some help-full extension, protocol based thing or any other suggestions.
question from:
https://stackoverflow.com/questions/66055761/extending-uiviewcontrollers-to-show-uialertcontroller-without-subclassing 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…