iOS 裡的畫面切換主要有三種模式,各自適用不同情境。搞懂它們的管理方式,架構就不容易亂。

tabBarController 屬性,可反查所屬的 TabBarController。tabBarItem 屬性,用來控制頁籤上的顯示資訊。viewControllers 屬性一次加入所有子控制器。window.rootViewController 後顯示 window。// a. 建立 tabBar 控制器 UITabBarController *tarbarVC = [[UITabBarController alloc] init]; self.window.rootViewController = tarbarVC; // b. 建立子控制器 UIViewController *c1 = [[UIViewController alloc] init]; c1.view.backgroundColor = [UIColor greenColor]; c1.tabBarItem.title = @"消息"; c1.tabBarItem.image = [UIImage imageNamed:@"tab_recent_nor"]; c1.tabBarItem.badgeValue = @"123"; UIViewController *c2 = [[UIViewController alloc] init]; c2.view.backgroundColor = [UIColor brownColor]; c2.tabBarItem.title = @"聯系人"; c2.tabBarItem.image = [UIImage imageNamed:@"tab_buddy_nor"]; UIViewController *c3 = [[UIViewController alloc] init]; c3.tabBarItem.title = @"動態"; c3.tabBarItem.image = [UIImage imageNamed:@"tab_qworld_nor"]; UIViewController *c4 = [[UIViewController alloc] init]; c4.tabBarItem.title = @"設置"; c4.tabBarItem.image = [UIImage imageNamed:@"tab_me_nor"]; // c. 加入所有子控制器 tarbarVC.viewControllers = @[c1, c2, c3, c4]; // d. 顯示主視窗 [self.window makeKeyAndVisible];
// 控制某個頁籤能不能被選中 - (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController;
切換目前顯示畫面的三種方式:改 selectedIndex、改 selectedViewController,或重新指定 viewControllers。
navigationController 屬性取得導覽控制器。navigationItem 控制。
UINavigationItem 屬於 MVC 中的 Model,封裝要顯示在導覽列上的資料:
下一個畫面左側返回按鈕標題的優先順序:
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated; // 壓疊 - (void)popViewControllerAnimated:(BOOL)animated; // 彈出頂端 - (void)popToViewController:(UIViewController *)viewController animated:(BOOL)animated; // 彈到指定控制器 - (void)popToRootViewControllerAnimated:(BOOL)animated; // 彈回根控制器
// 從下方彈出,模態期間其他畫面無法操作
- (void)presentViewController:(UIViewController *)viewControllerToPresent
animated:(BOOL)flag
completion:(void (^)(void))completion;
// 關閉模態視窗(在模態視城中呼叫)
- (void)dismissViewControllerAnimated:(BOOL)flag
completion:(void (^)(void))completion;
選擇上的建議:同層級的功能並列用 TabBarController;有明確父子層級與返回路徑用 NavigationController;需要使用者先完成某件事才能繼續(登入、表單、系統分享面板)則用模態呈現。