2017-05-15 41 views
0

我使用了一個輔助類來實現一些功能,包括一個UIAlertController,它可以從我的應用程序中的其他地方訪問,但是我有問題從助手類本身訪問它。UIAlertController在Swift 3.0中使用助手類

func showAlert(title: String, msg: String, controller: UIViewController) { 
     let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert) 
     let action = UIAlertAction(title: "OK", style: .default, handler: nil) 
     alert.addAction(action) 
     controller.present(alert, animated: true, completion: nil) 
    } 

從類之外,我可以沒有任何問題叫它:

Helper.helper.showAlert(title: "Not Internet Detected", msg: "Data Connectivity is Required", controller: self) 
從類中

不過,我得到一個錯誤:

showAlert(title: "Email in use, did you use another method to register", msg: "please try again", controller: self) 

我得到的錯誤是:

Cannot convert value of type Helper to expected type UIViewController

如何解決此問題問題?謝謝!

回答

3

您必須通過一個UIViewController實例作爲第三個參數。 self內的Helper類是Helper而不是UIViewController。這正是編譯器所抱怨的。警報只能從視圖控制器呈現。

考慮使用的UIViewController

extension UIViewController { 

    func showAlert(title: String, msg: String) { 
     let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert) 
     let action = UIAlertAction(title: "OK", style: .default, handler: nil) 
     alert.addAction(action) 
     self.present(alert, animated: true, completion: nil) 
    } 
} 

擴展可以調用的方法,其中從UIViewController繼承任何類。