我正在为几个函数使用一个帮助程序类,包括一个 UIAlertController,它可以从我的应用程序中的其他地方访问,但是我在从帮助程序类本身访问它时遇到了问题。
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 typeUIViewController
如何解决这个问题?谢谢!
最佳答案
您必须传递一个 UIViewController
实例作为第三个参数。 Helper
类中的 self
是 Helper
而不是 UIViewController
。这就是编译器所提示的。警报只能从 View Controller 中呈现。
考虑使用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
的类中调用该方法。
关于ios - UIAlertController 在 Swift 3.0 中使用辅助类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43986562/