UITabBarController是分栏控制器,可以在屏幕下方创建一个TabBar,TabBar上面有若干UITabBarItem实例。每个UITabBarItem管理一个视图控制器,点击不同的UITabBarItem时,会显示出不同的视图。
接着上一篇文章里的项目,在应用程序的委托类中,我创建好了一个导航控制器,我准备将它设为分栏控制器里的第一个视图控制器,先设置它的UITabBarItem。
//创建根视图控制器
RootController *rootController = [[RootController alloc] init];
//创建导航控制器
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:rootController];
UITabBarItem *tabBarItem1 = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:1];
navigationController.tabBarItem = tabBarItem1;
而后我创建一个书签视图控制器,并设置它的UITabBarItem。作为第二个视图。
//创建书签视图控制器
UIViewController *bookMark = [[UIViewController alloc] init];
bookMark.view.backgroundColor = [UIColor greenColor];
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];
label1.text =@"书签";
[bookMark.view addSubview:label1];
UITabBarItem *tabBarItem2 = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemBookmarks tag:2];
bookMark.tabBarItem = tabBarItem2;
创建一个下载视图控制器,作为第三个视图。
//下载视图控制器
UIViewController *downLoad = [[UIViewController alloc] init];
downLoad.view.backgroundColor = [UIColor cyanColor];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];
label2.text =@"下载";
[downLoad.view addSubview:label2];
UITabBarItem *tabBarItem3 = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemDownloads tag:3];
downLoad.tabBarItem = tabBarItem3;
最后,我将上面的视图控制器都加入到一个数组中,接着创建分栏控制器UITabBarController,并用之前创建的数组设置它的ViewControllers属性。让分栏控制器成为window的根控制器。
//创建视图控制器数组
NSArray *array = @[navigationController,bookMark,downLoad];
//创建分栏控制器
UITabBarController *tbc = [[UITabBarController alloc] init];
[tbc setViewControllers:array animated:YES];
//设置分栏控制器为window的根视图控制器
self.window.rootViewController = tbc;
运行结果截图: