我在另一个类的单独 swift 文件中有以下 Swift 3 代码。
class Login{
func showAlert(message :String){
let alertController2 = UIAlertController(title: "Error", message: "A error occured when checking credentials, try again later.", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController2.addAction(defaultAction)
self.present(alertController2, animated: true, completion: nil)
}
}
但我收到一个红色错误:
Use of unresolved identifier 'UIAlertController'
如何创建一个弹出窗口,通知用户出现问题?
最佳答案
首先你需要import UIKit
为了使UIAlertController
对您的类(class)可见。
此代码将获取当前 View Controller ,即使它是模态的。
func topViewController() -> UIViewController? {
guard var topViewController = UIApplication.shared.keyWindow?.rootViewController else { return nil }
while topViewController.presentedViewController != nil {
topViewController = topViewController.presentedViewController!
}
return topViewController
}
因此,您现在可以获得 Controller 并在其上显示警报:
topViewController()?.present(alertController2, animated: true, completion: nil)
关于ios - 如何显示来自另一个不是 UIViewController 的类的警报弹出窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42819859/