你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS --- UIViewController中的loadView使用場景

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

編輯:IOS開發綜合

問題

先看代碼, 新建一個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];

代碼如上, 不做過多解釋。三種方式其實殊途同歸。

 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved