UIViewController Present

2019-03-04 08:31发布

问题:

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.

回答1:

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 the viewDidLoad message is sent), but it is in the window hierarchy after it has been presented (when the viewDidAppear: message is sent).



回答2:

If you call presentViewController:animated:completion from 'viewDidLoad:' it won't work. And that is why:

The area of the screen used to define the presentation area is determined by the presentation context. By default, the presentation context is provided by the root view controller, whose frame is used to define the frame of the presentation context. However, the presenting view controller, or any other ancestor in the view controller hierarchy, can choose to provide the presentation context instead. In that case, when another view controller provides the presentation context, its frame is used instead to determine the frame of the presented view. This flexibility allows you to limit the modal presentation to a smaller portion of the screen, leaving other content visible.

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.