先看代碼, 新建一個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];
代碼如上, 不做過多解釋。三種方式其實殊途同歸。