使视图(从 initWithNibName 初始化)加载其所有子视图 [英] Make a view (initialized from initWithNibName) load all its subview

查看:25
本文介绍了使视图(从 initWithNibName 初始化)加载其所有子视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我从笔尖加载了一个视图控制器,并决定在幕后用它的一个子视图做一些事情.稍后,我将显示此视图控制器的视图.

Assuming I load a view controller from a nib, and decide to do something with one of its subview behind the scene. At a later moment in time, I would show the view of this view controller.

viewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil]; 
[viewController.someSubview doSomething];

//later on 
[mainView addSubview:viewController.view];

问题是,someSubview 对象在视图出现之前似乎没有被加载,所以方法 doSomething 没有被调用.到目前为止,我的解决方法是调用:

The problem is that, the someSubview object doesn't seem to be loaded until the view appears, so the method doSomething is not called. So far my workaround is to call:

[mainView addSubview:viewController.view];
[viewController.view removeFromSuperview];

先初始化viewcontroller的子视图.这个任务有没有更优雅的方法(比如 loadSubviews 方法或其他方法)?

to initialize the subviews of viewcontroller first. Is there any more elegant way (like a loadSubviews method or something) for this task?

推荐答案

首先,我会尝试简单地访问该属性:

First of all I would try simply accessing the property:

[viewController view];

这将强制延迟加载视图(以及子视图和插座等),这对您来说可能就足够了.默认情况下,视图控制器在您访问它之前不会加载它们的视图,因此这可能是您看到延迟的原因.

This will force the lazy load of the view (and thus the subviews and outlets etc.) and this might be enough for you. View controllers by default will not load their view until you access it so this might be why you are seeing a delay.

当您尝试访问 outlet 属性但实际上尚未绑定时,强制加载这样的通常是解决方案,例如 someSubview 在您的情况下.

Forcing a load like this is usually the solution when you are trying to access an outlet property but it hasn't actually been bound yet, like someSubview in your case.

您还可以通过添加视图但将其隐藏来稍微改进一下:

You can also improve things a bit by adding the view but making it hidden:

viewController.view.hidden = YES;
[mainView addSubview:viewController.view];

然后,当你想显示它时,不要调用 addSubview,而是这样做:

Then instead of calling addSubview when you want to show it, just do:

viewController.view.hidden = NO;

我在使用 UIViewAnimationTransitionFlipFromRight 等过渡在视图中制作动画时使用了这种方法.即使强制延迟加载视图,仍然存在明显的延迟,因此我使用它来稍微提高性能.

I've used this method when animating in views using the UIViewAnimationTransitionFlipFromRight etc. transitions. Even when forcing a lazy load of the view there is still a noticable lag, so I've used this to improve the performance a bit.

这篇关于使视图(从 initWithNibName 初始化)加载其所有子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆