码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-09-10 14:27:53      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:ios   uiviewcontroller   loadview   nib   

问题

先看代码, 新建一个UIViewController的子类TestViewController(包含nib文件),imageViewCourse和lbCourse是其两个属性,通过nib的IBOutlet方式添加。

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

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

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

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

解决方法

使用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_AVAILABLE_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];

代码如上, 不做过多解释。三种方式其实殊途同归。

版权声明:本文为博主原创文章,未经博主允许不得转载。

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

标签:ios   uiviewcontroller   loadview   nib   

原文地址:http://blog.csdn.net/icetime17/article/details/48337803

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!