简体   繁体   English

UIViewController存在

[英]UIViewController Present

I am trying to present a UIViewController with a UIView on it. 我正在尝试提出一个带有UIViewUIViewController

The following is the code I am trying in my viewDidLoad method. 以下是我在viewDidLoad方法中尝试的代码。

//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. 谢谢。

The solution is to move my code to the viewDidAppear method. 解决方案是将我的代码移至viewDidAppear方法。

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). 我假设view controller's view在已加载时(发送viewDidLoad消息时)不在窗口层次结构中,但是在呈现后(在viewDidAppear :message时)在窗口层次结构中已发送)。

If you call presentViewController:animated:completion from 'viewDidLoad:' it won't work. 如果您从“ viewDidLoad:”调用presentViewController:animated:completion ,则此方法将无效。 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 适用于iOS的View Controller编程指南:通过其他View Controller显示View Controller

In viewDidLoad frame of presenting view controller simply not set yet. 在呈现视图控制器的viewDidLoad框架中,尚未设置。 That is why you should present next controller only when presenting controller is on screen. 这就是为什么仅在显示控制器时才应显示下一个控制器的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM