在 iOS 中,UITabBarController 适合作為主要頁面切換,而 UINavigationController 适合處理每一頁內部的堆疊式導覽。把兩者整合,可以建立常見的多頁籤架構。
建立 UITabBarController,然後為每個頁籤建立一個 UINavigationController。每個 NavigationController 的 root,就是該頁籤的首頁。
UITabBarController *tabBarController = [[UITabBarController alloc] init]; FirstViewController *one = [[FirstViewController alloc] init]; one.title = @"聯絡人"; one.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemContacts tag:0]; UINavigationController *navFirst = [[UINavigationController alloc] initWithRootViewController:one]; [tabBarController addChildViewController:navFirst];
第二個頁籤也使用相同方式建立。完成後,把 tabBarController 設為 window 的 rootViewController。
在 FirstViewController 中,可以加入導覽列按鈕。點擊後,用 pushViewController 推入子頁。
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(selectRightAction:)]; self.navigationItem.rightBarButtonItem = rightButton;
這樣就能在頁籤內保留自己的導覽堆疊,而不会影響其他頁籤。
若 App 有多個主要功能入口,且每個入口都需要獨立導覽,適合使用這種結構。例如聯絡人、收藏、設定等頁面,各自拥有自己的 NavigationController。