Tab 這種樣式本質上是一個 radio-style 的單選切換,是當今主流的 layout 設計之一。它讓 App 的資訊架構一目了然,分工邏輯清楚,微信、時鐘這類 App 都是經典範例。


UITabBarController 繼承自 UIViewController,本質是一個 view controller container。tabBar,而 TabBar 持有一到多個 UITabBarItem。viewControllers 陣列中元素的順序,就是 TabBar 上呈現的順序。title;圖片則必須自己設定。UITabBarControllerDelegate 協定提供監控 TabBar 操作的回調。

@property(nonatomic, readonly) UITabBar *tabBar
唯讀,不應嘗試直接修改。要配置 item,請改 viewControllers。它存在的意義主要是為了在使用 UIActionSheet 的 showFromTabBar: 時提供 sender。
@property(nonatomic, copy) NSArray *viewControllers
赋值後,customizableViewControllers 的值會與之一致。若在 runtime 替換這個屬性,而原本選中的 index 已不存在,系統會預設選中 index 0。
- (void)setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated;
帶動畫的替換版本,是否使用可自行衡量。
@property(nonatomic, copy) NSArray *customizableViewControllers
指定哪些 tab 允許使用者自行拖動排序,對應上面那張超過 5 個 item 的示意圖。
@property(nonatomic, readonly) UINavigationController *moreNavigationController
系統為管理 customizableViewControllers 而自動建立的 NavigationController。
@property(nonatomic, assign) UIViewController *selectedViewController @property(nonatomic) NSUInteger selectedIndex
兩者互為表裡,可讀可寫。
// 讓使用者自訂 items 的排序,系統會自動彈出帶 Done 按鈕的編輯畫面 [self.tabBar beginCustomizingItems:@[item1, item3, item2]]; // 設定 item 的排列方式 self.tabBar.itemPositioning = UITabBarItemPositioningCentered; // 以下兩個屬性僅在 Centered 模式下才生效 self.tabBar.itemSpacing = 80.0f; self.tabBar.itemWidth = 30.0f;
UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"Test" image:nil tag:0];
// 標題文字顏色
[item setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}
forState:UIControlStateNormal];
[item setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor darkGrayColor]}
forState:UIControlStateSelected];
// 保留圖片原色。
// 預設情況下系統會取圖片的 alpha 通道自行生成單色圖,
// 這正是「設了自訂圖片卻沒生效」的最常見原因
item.image = [[UIImage imageNamed:@"color"]
imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
// 圖片內縮/外擴:正值向內縮,負值向外延伸
UIEdgeInsets insets;
insets.left = -5;
insets.right = -5;
item.imageInsets = insets;
// 標題位置偏移
UIOffset offset;
offset.horizontal = 30;
offset.vertical = -10;
[item setTitlePositionAdjustment:offset];
提供操作 Tab 時的回調,細節可對照官方文件。
對於內容展示類、功能導向的 App,最外層的資訊架構建議直接採用 Tab 模式——它對使用者最直覺,對開發分工也最友善。