UITabBarController学习归纳总结
UITabBarController学习笔记
一.基本知识
和UINavigationController类似,UITabBarController也可以用来控制多个页面导航,用户可以在多个视图控制器之间移动,并可以定制屏幕底部的选项卡栏。
借助屏幕底部的选项卡栏,UITabBarController不必像UINavigationController那样以栈的方式推入和推出视图,而是组建一系列的控制器(他们各自可以是UIViewController,UINavigationController,UITableViewController或任何其他种类的视图控制器),并将它们添加到选项卡栏,使每个选项卡对应一个视图控制器。
二.具体介绍
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 init]) {
? ?? ?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;
}