UITabBarController是选项卡栏导航控制器,显示效果是在页面底部有多个选项卡,通过点击不同选项卡可以在不同的ViewController之间进行切换。
这种对象的层次结构至少包含6个对象: 一个UITabBarController; 两个UIViewController; 一个UITabBar; 两个UITabBarItem;
UITabBarController是选项卡栏视图控制器,UITabBar是底部两个UITabBarItem的容器,管理两个UITabBarItem,每个UITabBarItem对应一个UIViewController,然后每个UIViewController都有自己的视图和视图控制器。
UITabBarController中有一个viewControllers属性,这是一个NSArray,包含选项卡控制器的视图控制器
下面来用代码创建一个UITabBarController: 下面是工程结构:
首先创建两个带xib文件的ViewController,分别为FirstViewController和SecondViewController 然后在AppDelegate.h中声明@property (strong, nonatomic) UITabBarController *tabBarController;,并添加协议UITabBarControllerDelegate
在.m中实现如下代码: - - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
- // Override point for customization after application launch.
-
- //第一个tab的viewController
- FirstViewController *firstViewController = [[FirstViewController alloc]init];
-
- //如果在这里指定tabitem标题,则在FirstViewController中指定self.tabBarItem.title则不生效
- firstViewController.title = @"First view";
-
- UITabBarItem *firstItem = [[UITabBarItem alloc]initWithTitle:@"First" image:nil tag:1];
- [firstItem setFinishedSelectedImage:[UIImage imageNamed:@"p1"] withFinishedUnselectedImage:[UIImage imageNamed:@"p1_f"]];
- firstViewController.tabBarItem = firstItem;
-
-
- SecondViewController *secondViewController = [[SecondViewController alloc]init];
-
- //构建TabBarItem
- UITabBarItem *secondItem = [[UITabBarItem alloc]initWithTitle:@"Second" image:nil tag:2];
-
- //设置选中和非选中状态下的图片
- [secondItem setFinishedSelectedImage:[UIImage imageNamed:@"p2_f"] withFinishedUnselectedImage:[UIImage imageNamed:@"p2"]];
- //右上角小图标
- [secondItem setBadgeValue:@"2"];
- //指定tabBarItem
- secondViewController.tabBarItem = secondItem;
- [secondItem release];
-
- //构建UITabBarController并指定代理为本身
- self.tabBarController = [[[UITabBarController alloc]init] autorelease];
- self.tabBarController.delegate = self;
-
- //为UITabBarController添加TabBarItem
- self.tabBarController.viewControllers = [NSArray arrayWithObjects:firstViewController,secondViewController, nil];
-
- [firstViewController release];
- [secondViewController release];
-
- //设置选中哪个tab
- // [self.tabBarController setSelectedIndex:0];
-
- //指定根视图
- self.window.rootViewController = self.tabBarController;
-
- self.window.backgroundColor = [UIColor whiteColor];
- [self.window makeKeyAndVisible];
- return YES;
- }
|