问题
先看代码, 新建一个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];
代码如上, 不做过多解释。三种方式其实殊途同归。
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-05 18:37:45