2017-07-04 28 views
1

當我使用我的類AlertView來顯示UIAlertView時,我將代理設置爲此類對象,並且期望alertView:clickedButtonAt運行,但是當我單擊UIAlertView上的按鈕時,它不起作用。爲什麼?謝謝!爲什麼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?") 
    } 
} 

備註:我會強烈建議使用UIAlertController代替UIAlertView

UIAlertView在iOS 8中已棄用。(請注意,UIAlertViewDelegate也是 也是d )要在iOS 8及更高版本中創建和管理警報,請使用帶有preferredStyle警報的UIAlertController,然後再使用 。

相關問題