本文在既有框架的基礎上,進一步加入 UITabBarController 控制項與頂部滾動欄,逐步完成一個多頁籤的專案布局。
首先來看看檔案布局:

1、在 DemMainViewController 中新增如下程式碼:
- (void)addMainController {
_tabController = [[UITabBarController alloc] init];
[_tabController.view setFrame:[self.view bounds]];
NSArray *classStringArray = [NSArray arrayWithObjects:@"DemFirstViewController", @"DemSecondViewController", @"DemThreeViewController", @"DemFourViewController", nil];
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i < [classStringArray count]; i++) {
Class c = NSClassFromString([classStringArray objectAtIndex:i]);
DemFSTFViewController *fstfViewController = [[c alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:fstfViewController];
[fstfViewController release];
[array addObject:nav];
[nav release];
}
[_tabController setViewControllers:array];
[self.view addSubview:_tabController.view];
}
說明:DemFirstViewController、DemSecondViewController、DemThreeViewController 與 DemFourViewController 四個類別皆繼承自 DemFSTFViewController 基類,作為 TabBarController 的四個分頁控制器。
2、在 DemFSTFViewController 中定義一個公開方法:
- (void)setTitle:(NSString *)title withImageName:(NSString *)imageName {
self.title = title;
self.tabBarItem.image = [UIImage imageNamed:imageName];
self.navigationItem.title = title;
}
說明:這個方法可以為每個繼承它的子類統一設定標題與 tabBarItem 圖示。
運行結果如下:

圖一

圖二
透過這種動態建立控制器並統一設定標題的做法,能有效減少重複程式碼,讓多頁籤應用的結構更加清晰易維護。