這篇是總結性質的筆記,把建立 view controller 的幾種方式與容易忽略的細節整理在一起。
前提條件:Main Interface 未設定。此時系統不會自動產生 Main.storyboard 的窗口,但我們仍可沿用系統提供的 storyboard 檔,只是要自己動手建立窗口的根控制器。
步驟一:在 AppDelegate 的 didFinishLaunchingWithOptions: 中建立 UIWindow:
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
步驟二:建立 UIStoryboard 物件並載入 Main.storyboard:
// 參數一:storyboard 檔名,不加副檔名
// 參數二:傳 nil 代表使用 [NSBundle mainBundle]
+ (UIStoryboard *)storyboardWithName:(NSString *)name
bundle:(NSBundle *)storyboardBundleOrNil;
// 實際用法
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];步驟三:從 storyboard 取得控制器。有兩種方式。
① 以箭頭指向的控制器作為根控制器:
- (UIViewController *)instantiateInitialViewController; UIViewController *vc = [storyboard instantiateInitialViewController];
這會取得 storyboard 中那個設為「Is Initial View Controller」的場景。若把粉色背景的那個場景設為起始點,執行後就會看到粉色的視窗。
② 以 Storyboard ID 建立:
- (UIViewController *)instantiateViewControllerWithIdentifier:(NSString *)identifier; UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"green"];
前提是該場景在屬性檢查器中設定了 Storyboard ID。以本例而言,綠色場景的 ID 設為 "green",即使起始點仍是粉色場景,這行程式碼仍會取得綠色那個。
取得 vc 後,記得設為 self.window.rootViewController 並呼叫 [self.window makeKeyAndVisible],否則畫面會是黑的。
同樣是在 Main Interface 未設定的前提下,先在 AppDelegate 中建立 UIWindow。
建立 xib 的兩種方式
① 新增 view controller 類別時勾選「Also create XIB file」,系統會產生一個與類別同名的 xib。
② 自行新增一個名稱可自訂的 xib,接著完成三個綁定設定:
載入方式
// 標準寫法 ViewController *vc = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; // 特殊寫法一 ViewController *vc = [[ViewController alloc] initWithNibName:nil bundle:nil]; // 特殊寫法二 ViewController *vc = [[ViewController alloc] init];
特殊寫法的底層邏輯
只有控制器的 init 方法在內部呼叫 initWithNibName:bundle:。當 nibName 傳入 nil 時,系統會依序尋找:
XMGView.xib)XMGViewController.xib)這解釋了一個常見困惑:為什麼有時候明明沒指定 xib 名稱,自訂的介面卻還是出現了——因為它命中了第一或第二條規則。
三種方式該怎麼選?Storyboard 適合流程明確、頁面間轉場多的 App;XIB 適合需要重複使用的自訂元件;純程式碼則在版面需要高度動態計算時最好維護。實際專案通常混用。