UIAlertAction - 处理动作

UIAlertAction - Handling Actions

我有一个帮手来显示我的警报

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)

我需要获取处理程序选项。我要将 "handler: nil" 更改为什么?

你应该可以做到这一点:

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
})

您可以向 showAlert 方法添加两个处理程序参数,一个用于确定操作,另一个用于取消操作。所以你的代码可能看起来像这样:

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
        })