我的应用程序中有几个四行块,根据用户的“是”或“否”操作决定流量
let alert = UIAlertController(title: "Delete", message: "Really delete?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: {(action) in self.deleteHistoryRecord(forRecordID: self.shistIDs[indexPath.row])}))
alert.addAction(UIAlertAction(title: "No", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
我想用前三行创建全局app方法/函数,然后返回Yes / No标志。管理处理程序的最佳方法是什么?在调用者中调用正确的方法?
答案 0 :(得分:1)
为了使全局功能能够显示警报,您可以使用类似这样的扩展名:
extension UIViewController {
func showAlert(_ completion:@escaping ()->()) {
let alert = UIAlertController(title: "Delete", message: "Really delete?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { (action) in
completion()
}))
alert.addAction(UIAlertAction(title: "No", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
然后每当你需要显示警告时,你只需要调用showAlert
通过你想要执行的完成(如果是的话);例如:从你的ViewController
开始,你可以使用它:
self.showAlert {
self.deleteHistoryRecord(forRecordID: self.shistIDs[indexPath.row])
}