2017-07-04 11 views
1

UIAlertViewの表示にクラスAlertViewを使用すると、このクラスオブジェクトにデリゲートを設定してalertView:clickedButtonAtを実行すると予想されますが、UIAlertViewでabuttonをクリックすると機能しません。どうして?ありがとう!UIAlertViewのデリゲートが機能しないのはなぜですか?

import UIKit 
@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 
    var window : UIWindow? 
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     window = UIWindow() 
     window!.rootViewController = UIViewController() 
     window!.rootViewController!.view.backgroundColor = .blue 
     window!.makeKeyAndVisible() 
     let a = AlertView() 
     a.show() 
     return true 
    } 

} 
class AlertView : UIViewController,UIAlertViewDelegate{ 
    var done : ((_ buttonIndex: Int)->Void)? 
    func show(){ 
     var createAccountErrorAlert: UIAlertView = UIAlertView() 

     createAccountErrorAlert.delegate = self 

     createAccountErrorAlert.title = "Oops" 
     createAccountErrorAlert.message = "Could not create account!" 
     createAccountErrorAlert.addButton(withTitle: "Dismiss") 
     createAccountErrorAlert.addButton(withTitle: "Retry") 

     createAccountErrorAlert.show() 

    } 
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int){ 
      print("Why delegate of alert view does not work?") 
    } 
} 
+1

UIAlertViewは使用しないでください。代わりにUIAlertControllerを使用する必要があります。 UIAlertViewはiOS9で廃止されました。 – Fogmeister

+0

あなたの注意をいただきありがとう、私はちょうど古いレガシーコード – TofJ

答えて

3

UIAlertViewインスタンスをローカル変数として宣言しているため、参照がありません。それをグローバル変数にすると、デリゲートメソッドが適切に実行できるようになります。

+0

クールを編集して修正!ありがとう:) – TofJ

2

私はそれがメモリ管理の問題に関係していると考えます。 createAccountErrorAlertは、ローカル変数としてshow()メソッドに宣言されています。これにより、変数の有効期間はメソッドを実行するライフタイムに依存します。次のように

溶液は、インスタンス変数としてcreateAccountErrorAlertを宣言することである。

class AlertView : UIViewController,UIAlertViewDelegate{ 
    var done : ((_ buttonIndex: Int)->Void)? 
    var createAccountErrorAlert: UIAlertView = UIAlertView() 

    func show(){ 
     createAccountErrorAlert.delegate = self 

     createAccountErrorAlert.title = "Oops" 
     createAccountErrorAlert.message = "Could not create account!" 
     createAccountErrorAlert.addButton(withTitle: "Dismiss") 
     createAccountErrorAlert.addButton(withTitle: "Retry") 

     createAccountErrorAlert.show() 

    } 
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int){ 
     print("Why delegate of alert view does not work?") 
    } 
} 

備考:私は非常にUIAlertViewの代わりUIAlertControllerを使用することをお勧めします:

UIAlertViewはiOS 8では非推奨です(UIAlertViewDelegateは ) iOS 8以降でアラートを作成して管理するには、代わりに アラートのpreferredStyleでUIAlertControllerを使用します。

関連する問題