ios - 如何更改 UIAlertController 的 UIAlertAction 处理程序中的全局值(添加函数)?

标签 ios swift uialertcontroller uialertaction

我想显示一个警报,我做到了。但有一个问题: 我无法更改全局值或在 UIAlertControllerUIAlertAction 处理程序中添加函数。例如:

let alertController = UIAlertController(title: "",
                                            message: "Do you want to leave ?", preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,
                             handler: {
                                action in
self.appDelegate.globalvalue = true 

})
alertController.addAction(cancelAction)
alertController.addAction(okAction)
if let popoverController = alertController.popoverPresentationController {
    popoverController.sourceView = sender as! UIView
    popoverController.sourceRect = sender.bounds
}
self.presentViewController(alertController, animated: true, completion: nil)

我在UIAlertControllerUIAlertAction的处理程序中添加了self.appDelegate.globalvalue = true,但是值self.appDelegate .globalvalue 始终为 false...self.appDelegate.globalvalue 未更改为 true...

如何更改 UIAlertControllerUIAlertAction 处理程序中的值?或者单击警报上的“确定”后可以更改全局值吗?谢谢你们的一切:)

最佳答案

如何获取对 AppDelegate 的引用?以下代码应该可以工作:

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var globalValue = false

}

class ViewController: UIViewController {

    var appDelegate: AppDelegate {
        return UIApplication.sharedApplication().delegate as! AppDelegate
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        let alert = UIAlertController(title: nil, message: "set global value to true", preferredStyle: .Alert)
        let action = UIAlertAction(title: "ok", style: .Default) { (action) in
            self.appDelegate.globalValue = true
            print("after: \(self.appDelegate.globalValue)")
        }
        alert.addAction(action)

        print("before: \(self.appDelegate.globalValue)")
        presentViewController(alert, animated: true, completion: nil)
    }

}

关于ios - 如何更改 UIAlertController 的 UIAlertAction 处理程序中的全局值(添加函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36566961/

相关文章:

swift - 如何在 Skscene SWIFT 中呈现 UIAlert

ios - 当我们可以使用数组在 swift 中返回多个值时,为什么要使用元组

iOS swift单例初始化方法

跨安装的 ios 唯一标识符

swift - 在我的设备上没有收到通知,只是在控制台中

ios - 纯代码构建集合但不执行 UICollectionViewDelegateFlowLayout

ios - iAd 横幅在 segue 上变白

swift - UIAlertController 取消完成永远不会被调用

iphone - iPhone反汇编中的objc_msgsend

xcode - Swift UIAlertController 获取文本字段文本