首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UIAlertAction -处理操作

UIAlertAction -处理操作
EN

Stack Overflow用户
提问于 2018-03-03 17:21:09
回答 2查看 351关注 0票数 1

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

代码语言:javascript
复制
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)
    }
}

如何管理视图控制器中的操作?

我是这样称呼这个小丑的;

代码语言:javascript
复制
AlertDialog.showAlert("Ok", message: "Some Message", viewController: self)

我需要得到处理程序的选项。我要把“处理程序:零”改为什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-03 17:31:17

可以向showAlert方法中添加两个处理程序参数,一个用于ok操作,另一个用于取消操作。因此,您的代码可能如下所示:

代码语言:javascript
复制
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中,您将调用:

代码语言:javascript
复制
AlertDialog.showAlert("Ok", message: "Some Message", viewController: self, okHandler: {
            //OK Action
        },cancelAction: {
            //Cancel Action
        })
票数 1
EN

Stack Overflow用户

发布于 2018-03-03 17:27:34

你应该能够做到这一点:

代码语言:javascript
复制
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)
}

然后,您可以这样使用它:

代码语言:javascript
复制
AlertDialog.showAlert("Ok", message: "Some Message", viewController: self, ok: { (alertAction) in 
    // do something for ok
}, cancel: { (alertAction) in
    // do something for cancel
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49086986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档