UITabBarController是選項(xiàng)卡欄導(dǎo)航控制器,顯示效果是在頁(yè)面底部有多個(gè)選項(xiàng)卡,通過(guò)點(diǎn)擊不同選項(xiàng)卡可以在不同的ViewController之間進(jìn)行切換。
這種對(duì)象的層次結(jié)構(gòu)至少包含6個(gè)對(duì)象:
一個(gè)UITabBarController;
兩個(gè)UIViewController;
一個(gè)UITabBar;
兩個(gè)UITabBarItem;
UITabBarController
是選項(xiàng)卡欄視圖控制器,UITabBar是底部?jī)蓚€(gè)UITabBarItem的容器,管理兩個(gè)UITabBarItem,每個(gè)UITabBarItem對(duì)
應(yīng)一個(gè)UIViewController,然后每個(gè)UIViewController都有自己的視圖和視圖控制器。
UITabBarController中有一個(gè)viewControllers屬性,這是一個(gè)NSArray,包含選項(xiàng)卡控制器的視圖控制器
下面來(lái)用代碼創(chuàng)建一個(gè)UITabBarController:
下面是工程結(jié)構(gòu):

首先創(chuàng)建兩個(gè)帶xib文件的ViewController,分別為FirstViewController和SecondViewController
然后在AppDelegate.h中聲明@property (strong,nonatomic)
UITabBarController *tabBarController;,并添加協(xié)議UITabBarControllerDelegate
在.m中實(shí)現(xiàn)如下代碼:
- - (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;
- }

