UITabbarController的介紹與使用

机械心發表於2024-06-30

UITabBarController 是 iOS 中用於管理和顯示選項卡介面的一個檢視控制器。它允許使用者在多個檢視控制器之間進行切換,每個檢視控制器對應一個選項卡。

主要功能

  1. 管理多個檢視控制器
    UITabBarController 管理一個檢視控制器陣列,每個檢視控制器對應一個選項卡。

  2. 顯示選項卡欄
    在螢幕底部顯示一個選項卡欄,允許使用者在檢視控制器之間進行切換。

  3. 處理選項卡切換
    響應使用者的選項卡切換操作,並相應地顯示相應的檢視控制器。

使用示例

建立和配置 UITabBarController

UITabBarController *tabBarController = [[UITabBarController alloc] init];

UIViewController *controller1 = [[UIViewController alloc] init];
controller1.view.backgroundColor = [UIColor redColor];
controller1.tabBarItem.title = @"新聞";

UIViewController *controller2 = [[UIViewController alloc] init];
controller2.view.backgroundColor = [UIColor yellowColor];
controller2.tabBarItem.title = @"影片";

UIViewController *controller3 = [[UIViewController alloc] init];
controller3.view.backgroundColor = [UIColor greenColor];
controller3.tabBarItem.title = @"推薦";

UIViewController *controller4 = [[UIViewController alloc] init];
controller4.view.backgroundColor = [UIColor lightGrayColor];
controller4.tabBarItem.title = @"我的";

[tabBarController setViewControllers:@[controller1, controller2, controller3, controller4]];

self.window.rootViewController = tabBarController;

透過設定 UITabBar 的屬性來自定義選項卡欄的外觀,例如:

  • 背景顏色
tabBarController.tabBarController.tabBar.barTintColor = [UIColor whiteColor];
  • 選中項顏色
tabBarController.tabBarController.tabBar.tintColor = [UIColor systemBlueColor];
  • 未選中項顏色
tabBarController.tabBarController.tabBar.unselectedItemTintColor = [UIColor grayColor];
  • Tab Bar Item 圖示

    在每個檢視控制器中設定 tabBarItem 屬性。

controller1.tabBarItem.image = [UIImage systemImageNamed:@"house.fill"];

處理選項卡切換事件

透過實現 UITabBarControllerDelegate 協議來處理選項卡切換事件

tabBarController.delegate = self;

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    NSLog(@"did select");
}

總結

UITabBarController 適用於需要在多個檢視控制器之間切換的應用程式。可以建立更加使用者友好和功能豐富的應用程式介面。

相關文章