Swift 3,Xcode 8.1 . 我想在 UIViewController
中显示 UIAlertController
.
我有方法:
private static func rootViewController() -> UIViewController {
// cheating, I know
return UIApplication.shared.keyWindow!.rootViewController!
}
static func presentAlert(_ message: String) {
let alertView = UIAlertController(title: "RxExample", message: message, preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "OK", style: .cancel) { _ in })
rootViewController().present(alertView, animated: true, completion: nil)
}
Full code of this class you can find here
我在 viewDidLoad
中调用presentAlert方法:
override func viewDidLoad() {
super.viewDidLoad()
DefaultWireframe.presentAlert("test")
...
}
并得到警告:
警告:尝试在UIViewController上显示UIAlertController:0x7f904ac0d930:0x7f904ad08040,其视图不在窗口层次结构中!
如何避免警告并显示警报?
It works when I try to show Alert in initial ViewController, but it doesn't work in another ViewController connected using push segue with initial VC.
2 回答
在viewDidLoad中,您的应用尚未向用户显示视图控制器,因此无法显示警报 . 尝试在viewDidAppear中执行该代码
我有类似的问题/案例,其中没有在另一个ViewController上推送的ViewController上显示操作表 . 它给出的错误也与你的错误相似 . 你所做的工作在普通的ViewControllers上运行得很好,但是对于推到其他ViewController上的ViewControllers却无效 .
我通过将类
UIAlertController
的对象作为我的类的实例变量而不是将其保持在触发函数内部来解决问题 .因此,在您的情况下,尝试在声明实例变量的类的顶部声明
var alertView: UIAlertController?
然后在您想要的触发函数中初始化它以使用它,如下所示:可能是苹果方面的一些错误,在维护参考时会引起这个问题 . 但是我上面写的作品很完美 .