2016-04-12 5 views
0

アラートを表示したいと思います。しかし、問題があります: グローバル値を変更することはできませんまたはUIAlertActionUIAlertControllerのハンドラで関数を追加することはできません。たとえば: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) 

私が行うことができますどのように

...私は UIAlertControllerUIAlertActionのハンドラで self.appDelegate.globalvalue = trueを追加し、その値 self.appDelegate.globalvalueself.appDelegate.globalvalueをtrueに変更されていない...常にfalseですのハンドブックの値を UIAlertActionに変更しますか?またはアラートで[OK]をクリックした後にグローバル値を変更することはできますか?皆さんありがとうございました:)

+0

自己なしで試しましたか?このコードはどこにありますか? AppdelegateまたはいくつかのviewController? – Miknash

+0

彼はクロージャ内から 'appDelegate'を参照するので、' self'を使う必要があります... –

+0

私は 'self'を使う必要があります。' AppDelegate.swift'の値を定義します。 – user2262304

答えて

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

} 
+0

ありがとうございました。このように 'var appDelegate:AppDelegate = UIApplication.sharedApplication()。delegate as! AppDelegate' – user2262304

+0

心配はありません。あなたの値が変更されたかどうかをどうやって確認しますか? –

+0

あなたのコードをありがとう、それは動作しますが、それは昨日動作しません、そして、実際には、 'var globalSDK:Video?'のようにSDKでグローバル値を定義しますが、 'Video '。このクラスでは、このビデオを使用する人の数を取得する関数があります。この関数を 'UIAlertAction'のハンドラで使用することはできません... 'globalSDK'はグローバル値で、なぜハンドラで使用できないのですか'UIAlertAction'の?私はハンドラからこの関数をテストして動作します、あなたは私にいくつかの助けを与えることができますか?ありがとうございます – user2262304