// 方式一:Storyboard 實例化 -> 可見 View
UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"meterEnlarge"];
return vc.view; // 正常顯示
// 方式二:手動 alloc/init -> 空白 View
ViewController_Meter_Enlarge_iPad *vc = [[ViewController_Meter_Enlarge_iPad alloc] init];
return vc.view; // 空白/不顯示
Storyboard 實例化會自動加載關聯的 View(Nib/Storyboard 場景),而 alloc/init 僅創建控制器對象,不會自動加載 View**,除非重寫 loadView 或有同名 .xib 文件。
init → 不加載 Viewview 屬性 → 觸發 loadViewloadView 默認行為:
.xib (繼承自 UIViewController) → [[NSBundle mainBundle] loadNibNamed:...]UIView (frame=CGRectZero)UITableViewController → 創建 UITableViewviewDidLoad → View 加載完成回調ViewController_Meter_Enlarge_iPad *vc = [[ViewController_Meter_Enlarge_iPad alloc]
initWithNibName:@"ViewController_Meter_Enlarge_iPad" bundle:nil];
return vc.view; // 正確加載 xib 視圖
@implementation ViewController_Meter_Enlarge_iPad
- (void)loadView {
self.view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.view.backgroundColor = [UIColor whiteColor];
// 純代碼添加子視圖、約束...
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
[btn setTitle:@"Test" forState:UIControlStateNormal];
[self.view addSubview:btn];
// 添加 AutoLayout 約束...
}
@end
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ViewController_Meter_Enlarge_iPad *vc = [sb instantiateViewControllerWithIdentifier:@"MeterEnlargeVC"];
return vc.view;
alloc/init 視為「未加載 View 狀態」,訪問 view 會觸發默認空白 View 創建。instantiateViewControllerWithIdentifier:,否則 segues、outlets、layout 全部失效。initWithNibName:bundle: 與 init 區別:前者指定 xib,後者依賴同名約定。理解 ViewController 視圖加載生命周期,區分 Storyboard/Nib/代碼三種創建模式,是 iOS 界面開發核心基本功。