I am trying to present a UIViewController
with a UIView
on it.
The following is the code I am trying in my viewDidLoad
method.
//create the view controller
UIViewController *controller = [[UIViewController alloc] init];
UIView *view = [[UIView alloc] init];
view.backgroundColor = [UIColor whiteColor];
controller.view = view;
//show the view
[self presentViewController:controller animated:YES completion:nil];
When I run the app, it is giving me the following error.
Warning: Attempt to present <UIViewController: 0x751fcd0> on <ViewController: 0x751d7a0> whose view is not in the window hierarchy!
What does this mean and where am I going wrong? Shouldn't it display a white view or am I understanding wrong?
Thanks.
If you call
presentViewController:animated:completion
from 'viewDidLoad:' it won't work. And that is why:View Controller Programming Guide for iOS: Presenting View Controllers from Other View Controllers
In
viewDidLoad
frame of presenting view controller simply not set yet. That is why you should present next controller only when presenting controller is on screen.The solution is to move my code to the
viewDidAppear
method.I'm assuming that the
view controller's view
is not in the window hierarchy at the point that it has been loaded (when theviewDidLoad
message is sent), but it is in the window hierarchy after it has been presented (when theviewDidAppear
: message is sent).