【问题标题】:UIAlertAction - Handling ActionsUIAlertAction - 处理动作
【发布时间】:2018-03-03 17:21:09
【问题描述】:

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

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”改成什么?

【问题讨论】:

标签: ios swift handler uialertaction


【解决方案1】:

您可以在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
        })

【讨论】:

  • 鉴于这个问题,我认为通过展示如何使用新参数的示例来回答会有所帮助。
【解决方案2】:

你应该可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    相关资源
    最近更新 更多