二. 具体介绍
1. 通过代码的方式创建UITabBarController界面
代码的位置应该放在xxxAppDelegate.m 中的applicationDidFinishLaunching:方法中,因为Tab Bar Controller通常是为应用窗口提供根视图,所以需要在程序启动后,窗口显示前创建Tab Bar Controller。具体创建步骤为:
(1) 创建一个新的UITabBarController对象
(2) 为每一个Tab创建一个root view controller
(3) 把这些root view controllers添加到一个array中,再把这个array分配给tab bar controller的viewControllers属性
(4) 把tab bar controller's view添加到应用程序主窗口
例子:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
tabBarController = [[UITabBarController alloc] init];
MyViewController* vc1 = [[MyViewController alloc] init];
MyOtherViewController* vc2 = [[MyOtherViewController alloc] init];
NSArray* controllers = [NSArray arrayWithObjects:vc1, vc2, nil];
tabBarController.viewControllers = controllers;
// Add the tab bar controller's current view as a subview of the window
[window addSubview:tabBarController.view];
}
2. 通过代码的方式创建TabBarItem
Tab Bar Controller的每个选项卡都得有一个UITabBarItem,可以在其root view controller初始化时创建并添加UITabBarItem。
例子:
- (id)init {
if (self = [super initWithNibName:@"MyViewController" bundle:nil]) {
self.title = @"My View Controller";
UIImage* anImage = [UIImage imageNamed:@"MyViewControllerImage.png"];
UITabBarItem* theItem = [[UITabBarItem alloc] initWithTitle:@"Home" image:anImage tag:0];
self.tabBarItem = theItem;
[theItem release];
}
return self;
}