iOS --- UIViewController中的loadView使用情境

來源:互聯網
上載者:User

iOS --- UIViewController中的loadView使用情境
問題

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

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

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.