在實際專案中,UITabBarController 搭配 UINavigationController 是非常常見的結構。TabBar 負責主要功能切換,NavigationController 則負責每一頁內部的堆疊導覽。
通常會在 AppDelegate 中建立 window、tabBarController,再把各個功能頁包進 NavigationController,最後加入 tabBarController。
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.tabBarController = [[UITabBarController alloc] init];
FirstViewController *one = [[FirstViewController alloc] init];
SecondViewController *second = [[SecondViewController alloc] init];
UINavigationController *navFirst = [[UINavigationController alloc] initWithRootViewController:one];
UINavigationController *navSecond = [[UINavigationController alloc] initWithRootViewController:second];
[self.tabBarController addChildViewController:navFirst];
[self.tabBarController addChildViewController:navSecond];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];每個主要頁面都可以設定標題與圖示,讓使用者在底部標籤欄辨識目前所在頁面。
one.title = @"聯絡人";
one.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"one" image:[UIImage imageNamed:@""] selectedImage:nil];在主要頁面中,可以透過 navigationController push 二級頁面,形成堆疊式導覽。
BackViewController *back = [[BackViewController alloc] init];
back.title = @"第二視圖層";
[self.navigationController pushViewController:back animated:NO];這個模板幾乎涵蓋多數 App 的基本導覽需求。只要掌握 rootViewController 設定、TabBarItem 配置與 push 流程,就能快速建立可擴充的專案骨架。