在 TabBarController 的頁面中,往往還需要在各分頁內部進行「一層一層」的導航,這就牽涉到如何讓 TabBarController 與 NavigationController 一起運作。我整理了實務上常見的三種做法,供大家參考。
先用 TabBarController 建立 XIB,拉出各個 Tabbar。若需要進入下一頁,就在目前頁面建立對應關係,並以 present 的方式彈出包在 NavigationController 裡的下一層視圖:
EDUThreeViewController *th = [[EDUThreeViewController alloc] initWithNibName:@"EDUThreeViewController" bundle:nil];
UINavigationController *n = [[UINavigationController alloc] initWithRootViewController:th];
[self presentViewController:n animated:YES completion:nil];
這種方式最直接,但它比較偏向「彈出下一級視圖」的用法。
一樣先建立 TabBarController 的 XIB,接著從元件庫把 NavigationController 直接拖進對應的 Tab 上(依需要也可以拖入 TabBarItem)。拖入 NavigationController 的那個分頁,會自動帶有一個 NavigationBar,之後就能在該分頁裡自由設計導航堆疊。
這種做法的缺點是:推入下一級視圖時,底部的 TabBar 也會一起被帶過去。若不希望顯示,可用底下的寫法把它隱藏:
EDUStuViewController *stuViewController = [[EDUStuViewController alloc] init];
stuViewController.hidesBottomBarWhenPushed = YES; // 推入時隱藏 TabBar
[self.navigationController pushViewController:stuViewController animated:YES];
前面兩種偏重在 XIB 中操作,第三種則完全用程式碼完成,在 delegate 裡把 TabBarController 與各分頁的 NavigationController 結合起來:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds];
// TabBar 的第一個分頁
EDUaaViewController *aa = [[EDUaaViewController alloc] initWithNibName:@"EDUaaViewController" bundle:nil];
UINavigationController *aaNav = [[UINavigationController alloc] initWithRootViewController:aa];
// TabBar 的第二個分頁
EDUbbViewController *bb = [[EDUbbViewController alloc] initWithNibName:@"EDUbbViewController" bundle:nil];
UINavigationController *bbNav = [[UINavigationController alloc] initWithRootViewController:bb];
// 把各分頁的 NavigationController 放進陣列
NSArray *controllerArray = [[NSArray alloc] initWithObjects:aaNav, bbNav, nil];
// 建立 TabBarController(記得在 .h 中先宣告)
tabBarController = [[UITabBarController alloc] init];
tabBarController.delegate = self;
tabBarController.viewControllers = controllerArray;
tabBarController.selectedIndex = 0;
[[tabBarController.tabBar.items objectAtIndex:0] setTitle:@"體檢數據"];
[[tabBarController.tabBar.items objectAtIndex:1] setTitle:@"健康檔案"];
[self.window addSubview:tabBarController.view];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
這種做法的核心觀念是:每一個 Tab 分頁,其 root 都是一個 NavigationController,而 TabBarController 管理的是這群 NavigationController。如此一來,每個分頁各自擁有自己的導航堆疊,彼此互不干擾,是最靈活、也最推薦的組合方式。