您的位置:首页 > 产品设计 > UI/UE

iOS --- UIViewController中的loadView使用场景

2015-09-11 13:03 597 查看
对之前的内容进行了补充及截图说明。

因为还要做其他的实验, 所以使用了Test1ViewController及实例test1VC,而之前是使用TestViewController及testViewController,这点应该不影响大家阅读。

问题

先看代码, 新建一个UIViewController的子类TestViewController(包含nib文件):

imageViewCourse和lbCourse是其两个属性,通过nib的IBOutlet方式添加。如下图:

[thead]
[/thead]
新建Test1ViewController添加IBOutlet


使用如下代码进行UIViewController之间的跳转:

TestViewController *testViewController = [[TestViewController alloc] initWithNibName:@"TestViewController" bundle:nil];

testViewController.imageViewCourse.image = image;
testViewController.lbCourse.text = course;

[self presentViewController:testViewController animated:YES completion:nil];


我们使用nib来加载一个TestViewController并对其属性赋值, 然后跳转。问题在于执行完initWithNibName之后,testViewController.imageViewCourse和testViewController.lbCourse都为nil, 则表现出来的是跳转到TestViewController之后, 其中的imageViewCourse和lbCourse中没有内容。如下图:

[thead]
[/thead]
IBOutlet未更新内容断点调试


解决方法

使用loadView方法触发nib中UIView的加载。

@property(null_resettable, nonatomic,strong) UIView *view; // The getter first invokes [self loadView] if the view hasn't been set yet. Subclasses must call super if they override the setter or getter.
- (void)loadView; // This is where subclasses should create their custom view hierarchy if they aren't using a nib. Should never be called directly.
- (void)loadViewIfNeeded NS_***AILABLE_IOS(9_0); // Loads the view controller's view if it has not already been set.


即:

TestViewController *testViewController = [[TestViewController alloc] initWithNibName:@"TestViewController" bundle:nil];
[testViewController view];
//[testViewController loadView];
//[testViewController loadViewIfNeeded];

testViewController.imageViewCourse.image = image;
testViewController.lbCourse.text = course;

[self.navigationController presentViewController:testViewController animated:YES completion:nil];


结果如下图:

[thead]
[/thead]
IBOutlet更新内容断点调试


代码如上, 不做过多解释。三种方式其实殊途同归。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: