0

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

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)

我添加了ofself.appDelegate.globalvalue = true的处理程序,但值始终为 false...未更改为 true...UIAlertActionUIAlertControllerself.appDelegate.globalvalueself.appDelegate.globalvalue

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

4

1 回答 1

0

你如何得到参考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)
    }

}
于 2016-04-12T08:10:41.193 回答