首先我们看一下它的view层级图:
1.手动创建UITabBarController
最常见的创建UITabBarController的地方就是在application delegate中的 applicationDidFinishLaunching:方法,因为UITabBarController通常是作为整个程序的rootViewController的,我们需要在程序的window显示之前就创建好它,具体步骤如下:
1.1、创建一个UITabBarController对象
1.2、创建tabbarcontroller中每一个tab对应的要显示的对象
1.3、通过UITabBarController的viewController属性将要显示的所有content viewcontroller添加到UITabBarController中
1.4、通过设置UITabBarController对象为window.rootViewController,然后显示window
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
TabBarFirstViewController *viewController1,
TabBarSecondViewController *viewController2;
viewController1 = [[SvTabBarFirstViewController alloc] initWithNibName:nil bundle:nil];
viewController1.title = @"First";
viewController2 = TabBarSecondViewController alloc] initWithNibName:nil bundle:nil];
viewController2.title = @"Second";
self.tabBarController = [[[UITabBarController alloc] init] autorelease];
self.tabBarController.delegate = self;
self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, nil];
[viewController1 release];
[viewController2 release];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
2.UITabBarItem
UITabBar上面显示的每一个Tab都对应着一个ViewController,我们可以通过设置viewcontroller.tabBarItem属性来改变tabbar上对应的tab显示内容。否则系统将会根据viewController的title自动创建一个,该tabBarItem只显示文字,没有图像。当我们自己创建UITabBarItem的时候,我们可以显示的指定显示的图像和对应的文字描述。当然还可以通过setFinishedSelectedImage:withFinishedUnselectedImage:方法给选中状态和飞选中状态指定不同的图片。下面看个自己创建UITabBarItem的小例子:
UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"Second" image:nil tag:2];
[item setFinishedSelectedImage:[UIImage imageNamed:@"second.png"]
withFinishedUnselectedImage:[UIImage imageNamed:@"first.png"]];
viewController2.tabBarItem = item;
[item release];
3.UITabBarControllerDelegate
通过代理我们可以监测UITabBarController的当前选中viewController的变化,以及moreViewController中对编辑所有viewController的编辑。通过实现下面方法:
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController;