我有一个助手来显示我的警报
import UIKit
class AlertDialog {
class func showAlert(_ title: String, message: String, viewController: UIViewController) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(OKAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
viewController.present(alertController, animated: true, completion: nil)
}
}如何管理视图控制器中的操作?
我是这样称呼这个小丑的;
AlertDialog.showAlert("Ok", message: "Some Message", viewController: self)我需要得到处理程序的选项。我要把“处理程序:零”改为什么?
发布于 2018-03-03 17:31:17
可以向showAlert方法中添加两个处理程序参数,一个用于ok操作,另一个用于取消操作。因此,您的代码可能如下所示:
class AlertDialog {
class func showAlert(_ title: String, message: String, viewController: UIViewController,
okHandler: (() -> Swift.Void),
cancelHandler: (() -> Swift.Void)) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: okHandler)
alertController.addAction(OKAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: cancelHandler)
alertController.addAction(cancelAction)
viewController.present(alertController, animated: true, completion: nil)
}
}在您的viewController中,您将调用:
AlertDialog.showAlert("Ok", message: "Some Message", viewController: self, okHandler: {
//OK Action
},cancelAction: {
//Cancel Action
})发布于 2018-03-03 17:27:34
你应该能够做到这一点:
class func showAlert(_ title: String, message: String, viewController: UIViewController, ok: ((UIAlertAction) -> Void)?, cancel: ((UIAlertAction) -> Void)?) {
let okAction = UIAlertAction(title: "Ok", style: .default, handler: ok)
let cancelAction = UIAlertAction(title: "Ok", style: .default, handler: cancel)
}然后,您可以这样使用它:
AlertDialog.showAlert("Ok", message: "Some Message", viewController: self, ok: { (alertAction) in
// do something for ok
}, cancel: { (alertAction) in
// do something for cancel
})https://stackoverflow.com/questions/49086986
复制相似问题