UITabBarController 是 iOS 裡最常見的底部導覽元件,幾乎每個多頁面的 App 都會用到。以下示範如何以純程式碼建立一個含四個分頁的 TabBar,並為分頁加上未讀數字提示。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
HomeViewController *view1 = [[HomeViewController alloc] init];
MessageViewController *view2 = [[MessageViewController alloc] init];
SearchViewController *view3 = [[SearchViewController alloc] init];
SettingViewController *view4 = [[SettingViewController alloc] init];
UINavigationController *v1 = [[UINavigationController alloc] initWithRootViewController:view1];
UINavigationController *v2 = [[UINavigationController alloc] initWithRootViewController:view2];
UINavigationController *v3 = [[UINavigationController alloc] initWithRootViewController:view3];
UINavigationController *v4 = [[UINavigationController alloc] initWithRootViewController:view4];
NSArray *viewControllers = [NSArray arrayWithObjects:v1, v2, v3, v4, nil];
UITabBarController *mainViewController = [[UITabBarController alloc] init];
mainViewController.viewControllers = viewControllers;
[self.window setRootViewController:mainViewController];
return YES;
}
每個分頁的標題與圖示提示,都在自己的初始化方法中設定:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = @"首頁";
self.tabBarItem.badgeValue = @"New";
}
return self;
}
-(void)loadView
{
UIView *view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
view.backgroundColor = [UIColor whiteColor];
self.view = view;
}
為什麼每頁都包一層 UINavigationController:TabBarController 本身不提供頁面堆疊能力。若各分頁需要「點進去、再返回」的層級結構,就必須把每個 root 控制器包進 UINavigationController 再交給 TabBar。
數字提示的設定:tabBarItem.badgeValue 接受的是 NSString,因此數字也要寫成字串,例如 self.tabBarItem.badgeValue = @"8";。設為 nil 即可移除提示。
關於 applicationIconBadgeNumber:那個屬性控制的是桌面圖示上的紅色數字,與 TabBar 上的提示是兩套獨立機制,別混淆。
記憶體管理:以上範例採用 ARC 語境撰寫,因此不需手動 release。若專案仍使用 MRC,記得在適當時機釋放建立的控制器物件。