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

时间:2016-04-12 07:54:11

标签: ios swift uialertcontroller uialertaction

我想表示警告,我做到了。但有个问题: 我无法更改全局值或在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) self.appDelegate.globalvalue = true的处理程序中添加函数。例如:

UIAlertAction

我在UIAlertController self.appDelegate.globalvalue的处理程序中添加self.appDelegate.globalvalue,但值UIAlertAction始终为false ... UIAlertController未更改为真...

如何更改{{1}} {{1}}处理程序中的值?或者我可以在警报上单击“确定”后更改全局值吗?谢谢你们所有人:)

1 个答案:

答案 0 :(得分: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)
    }

}
相关问题