自學者常嘗試在單一 UIViewController 內手動 addSubview/removeFromSuperview 切換子視圖,導致:
viewWillAppear 等) 不被呼叫。| 需求 | 推薦方案 | 核心類別 |
|---|---|---|
| 底部標籤切換 (3-5 頁) | UITabBarController | UITabBarController, UINavigationController |
| 鑽取式導航 (列表→詳情) | UINavigationController | pushViewController/popViewController |
| 模態呈現 (登入、設定) | presentViewController | modalPresentationStyle |
| 自定義容器 (分割視圖、抽屜) | Container View Controller | addChild/removeFromParent |
// 錯誤做法:手動管理 view
// 正確做法:使用 UITabBarController
UITabBarController *tabBar = [[UITabBarController alloc] init];
tabBar.viewControllers = @[
[self navWithRoot:vc1 title:@"首頁" image:@"home"],
[self navWithRoot:vc2 title:@"音樂" image:@"music"],
[self navWithRoot:vc3 title:@"發現" image:@"discover"],
[self navWithRoot:vc4 title:@"我的" image:@"mine"]
];
self.window.rootViewController = tabBar;
// 輔助:包裝導航控制器
- (UINavigationController*)navWithRoot:(UIViewController*)vc title:(NSString*)t image:(NSString*)img {
vc.title = t;
vc.tabBarItem.image = [UIImage imageNamed:img];
return [[UINavigationController alloc] initWithRootViewController:vc];
}
UITabBarAppearance (iOS 13+) 統一樣式,避免各頁面重複設定。restorationIdentifier + encodeRestorableState 實現 App 重啟恢復分頁。結論:拥抱蘋果提供的容器控制器,專注於業務視圖控制器邏輯,才是 iOS 開發的正道。