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];
-
-
-
- FirstViewController *firstViewController = [[FirstViewController alloc]init];
-
-
- 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];
-
-
- UITabBarItem *secondItem = [[UITabBarItem alloc]initWithTitle:@"Second" image:nil tag:2];
-
-
- [secondItem setFinishedSelectedImage:[UIImage imageNamed:@"p2_f"] withFinishedUnselectedImage:[UIImage imageNamed:@"p2"]];
-
- [secondItem setBadgeValue:@"2"];
-
- secondViewController.tabBarItem = secondItem;
- [secondItem release];
-
-
- self.tabBarController = [[[UITabBarController alloc]init] autorelease];
- self.tabBarController.delegate = self;
-
-
- self.tabBarController.viewControllers = [NSArray arrayWithObjects:firstViewController,secondViewController, nil];
-
- [firstViewController release];
- [secondViewController release];
-
-
-
-
-
- self.window.rootViewController = self.tabBarController;
-
- self.window.backgroundColor = [UIColor whiteColor];
- [self.window makeKeyAndVisible];
- return YES;
- }