在 Storyboard 設計好介面,但在 AppDelegate 的 didFinishLaunchingWithOptions 中以 [ViewController new] 方式初始化並設為 rootViewController,導致畫面顯示空白,控件全數消失。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
ViewController *vc = [ViewController new];
vc.dictUserInfo = @{@"User": [[NSUserDefaults standardUserDefaults] objectForKey:@"User"],
@"Pwd" : [[NSUserDefaults standardUserDefaults] objectForKey:@"Pwd"],
@"IP" : [[NSUserDefaults standardUserDefaults] objectForKey:@"IP"]};
self.window.rootViewController = vc;
return YES;
}
使用 [ViewController new] 會建立一個全新的 ViewController 實例,這個實例**不會**載入 Storyboard 中設計的視圖層級,因此 viewDidLoad 中的 self.txtUser 等 IBOutlet 全為 nil,自然看不到任何控件。
應從 Storyboard 實例化 ViewController,確保視圖層級正確載入:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"ViewController"];
// 或使用初始視圖控制器
// ViewController *vc = [storyboard instantiateInitialViewController];
vc.dictUserInfo = @{@"User": [[NSUserDefaults standardUserDefaults] objectForKey:@"User"],
@"Pwd" : [[NSUserDefaults standardUserDefaults] objectForKey:@"Pwd"],
@"IP" : [[NSUserDefaults standardUserDefaults] objectForKey:@"IP"]};
self.window.rootViewController = vc;
return YES;
}
記得在 Storyboard 中為 ViewController 設定 Storyboard ID(例如 "ViewController"),或勾選 Is Initial View Controller。
Info.plist 設定 Main storyboard file base name,系統會自動載入初始視圖控制器,通常不需在 AppDelegate 手動處理。prepareForSegue 或透過 window.rootViewController 取得後再設定屬性。