LoginSignup
0
0

More than 5 years have passed since last update.

手動要求 view controller 載入 nib (with Swift)

Last updated at Posted at 2016-08-19

日前有碰到一些問題,就是當我在進行畫面邏輯的時候,
因為使用的 view controller 還沒有被顯示出來、 view 還沒被初始化、 nib 中的畫面元件也還沒被載入

@IBOutlet 繫結的畫面元件在程式碼中預設是以 implicitly unwrapped optional 的型態存在,如 UILabel!UIButton! 等等;因此這時候取用這些元件,因為在 runtime 中取得 nil 值,就 crash 了。

手動載入 nib

在 view controller 取用 view 的時候,會載入需要的 nib 檔案,
因此我們只需要手動做到這件事即可。

官方這麼寫

The nib file you specify is not loaded right away. It is loaded the first time the view controller'€™s view is accessed.

接下來我們會用 MYViewController 當例子,這個 class

  • UIViewController 的子類別
  • 需要透過 nib 來設定畫面元件

iOS 9 的場合

var myViewController = MYViewController(nibName: "MYViewController", bundle: nil)
myViewController.loadViewIfNeeded()

呼叫 loadViewIfNeeded() 這個方法即可

iOS 8 以下的場合

因為上一小節提到的方法是在 iOS 9 開始才有的,因此在 iOS 8 只能用比較笨的方法,去呼叫 view controller 主要的 view ,觸發他載入 nib 。

var myViewController = MYViewController(nibName: "MYViewController", bundle: nil)
let _ = myViewController.view

因為這個 view 也不需要使用,就使用 _ 來承接這個值即可。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0