一.基本知识
和UINavigationController类似,UITabBarController也可以用来控制多个页面导航,用户可以在多个视图控制器之间移动,并可以定制屏幕底部的选项卡栏。
借助屏幕底部的选项卡栏,UITabBarController不必像UINavigationController那样以栈的方式推入和推出视图,而是组建一系列的控制器(他们各自可以是UIViewController,UINavigationController,UITableViewController或任何其他种类的视图控制器),并将它们添加到选项卡栏,使每个选项卡对应一个视图控制器。
二.具体介绍(使用XCode4.2 SDK5beta)
1:新建空的工程。
2:添加UIViewController subclass到工程里,(勾选with XIB for user interface)
3:选择2中添加的一个(如AAA)作为rootViewController,用于承载其他页面
4:在XXXAppDelegate.m中的applicationDidFinishLaunching中,实例化AAA,并设置其为rootViewController
self.window.rootViewController=aAAA;
5:由于选定了AAA页面作为宿主页面,故需要在AAA页面内添加UITableBarController.
在AAA.h声明UITableBarController
在AAA.m中实例化UITableBarController,设置它的viewControllers后,并添加到该页面的subView中。
(设置viewControllers的作用就是点击某个item就跳转到对应的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
[self.view addSubview:tabBarController.view];
}
6.创建各个连接各个view的TabBarItem
Tab Bar Controller的每个选项卡都得有一个UITabBarItem,可以在对应的View的初始化时创建并添加UITabBarItem。
例子:
- (id)init {
if (self) {
self.title = @"My View Controller";
UIImage* anImage = [UIImage imageNamed@"MyViewControllerImage.png"];
UITabBarItem* theItem = [[UITabBarItem alloc] initWithTitle@"Home" image:anImage tag:0];
self.tabBarItem = theItem;
}
return self;
}
PS:应当可以在rootViewController中统一添加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;
}
UITabBarControllerDelegate
通过代理我们可以监测UITabBarController的当前选中viewController的变化,以及moreViewController中对编辑所有viewController的编辑。通过实现下面方法:
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController;
该方法用于控制TabBarItem能不能选中,返回NO,将禁止用户点击某一个TabBarItem被选中。但是程序内部还是可以通过直接setSelectedIndex选中该TabBarItem。
下面这三个方法主要用于监测对moreViewController中对view controller的edit操作
- (void)tabBarController:(UITabBarController *)tabBarController willBeginCustomizingViewControllers:(NSArray *)viewControllers; - (void)tabBarController:(UITabBarController *)tabBarController willEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed; - (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed;