UIAlertController code runs, but doesn't present an alert

China☆狼群 提交于 2020-01-05 07:28:07

问题


I am trying to make an in-app popup alert using swift and I have run into an error that I know nothing about.

Here is the code I use to present my alert:

let welcomeAlert = UIAlertController(title: "Welcome!", message: “message here”, preferredStyle: UIAlertControllerStyle.Alert)
welcomeAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(welcomeAlert, animated: true, completion: nil)

println("welcome alert displayed!")

The error I'm getting back says this:

Warning: Attempt to present <UIAlertController: 0x7b89a950> on <MyApp.RootClientViewController: 0x7aea8fb0> whose view is not in the window hierarchy!

This is immediately followed by a printed statements stating welcome alert displayed!.

So my code is certainly running, but for some reason, it won't display the alert...

What am I doing wrong?


回答1:


The error message tells you the answer: "view is not in the window hierarchy!" means self.view is not on screen when the call is made (technically it means UIApplication.sharedApplication().keyWindow is not an ancestor of self.view).

Usually this happens when presenting a view controller in viewDidLoad() or viewWillAppear(animated: Bool). Wait for viewDidAppear(animated: Bool), present from UIApplication.sharedApplication().delegate.window.rootViewController or present from UIApplication.sharedApplication().keyWindow.rootViewController.



来源:https://stackoverflow.com/questions/27197677/uialertcontroller-code-runs-but-doesnt-present-an-alert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!