课堂实例3:
集成Tab Bar Controller和Navigation Controller
实例代码:
<pre name="code" class="objc"> [self.window makeKeyAndVisible];
/*思路:
*1.创建若干个子视图控制器(它们是并列的关系)
* 1.1创建UITabBarItem实例,赋值给相应的子视图控制器(2中方法)
*2.创建一个数组,将已创建的子视图控制器,添加到数组中
*3.创建UITabBarController实例
*4.tabBarController.viewControllers = viewControllers;
*5.添加到window的rootViewController中(显示出来)
*/
homeViewController *vc1 = [[homeViewController alloc]init];
UINavigationController *homeNav = [[UINavigationController alloc]initWithRootViewController:vc1];
UITabBarItem *homeItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:1];
vc1.tabBarItem = homeItem;
vc1.title = @"首页";
vc1.view.backgroundColor = [UIColor redColor];
//消息页
MesageViewController *vc2 = [[MesageViewController alloc]init];
UINavigationController *mesNav = [[UINavigationController alloc]initWithRootViewController:vc2];
UITabBarItem *mesItem = [[UITabBarItem alloc]initWithTitle:@"搜索" image:[UIImage imageNamed:@"alarm"] tag:4];
vc2.tabBarItem = mesItem;
vc2.title = @"消息";
vc2.view.backgroundColor = [UIColor blueColor];
//搜索页
SearchViewController *vc3 = [[SearchViewController alloc]init];
UINavigationController *sacNav = [[UINavigationController alloc]initWithRootViewController:vc3];
UITabBarItem *sacItem = [[UITabBarItem alloc]initWithTitle:@"搜索" image:[UIImage imageNamed:@"alarm"] tag:3];
vc3.tabBarItem = sacItem;
vc3.title = @"搜索";
vc3.view.backgroundColor = [UIColor grayColor];
//设置页
settingViewController *vc4 = [[settingViewController alloc]init];
UINavigationController *setNav = [[UINavigationController alloc]initWithRootViewController:vc4];
UITabBarItem *setItem = [[UITabBarItem alloc]initWithTitle:@"搜索" image:[UIImage imageNamed:@"alarm"] tag:4];
vc4.tabBarItem = setItem;
//其它页
OtherViewController *vc5 = [[OtherViewController alloc]init];
UINavigationController *othNav = [[UINavigationController alloc]initWithRootViewController:vc5];
UITabBarItem *othItem = [[UITabBarItem alloc]initWithTitle:@"搜索" image:[UIImage imageNamed:@"alarm"] tag:5];
vc5.tabBarItem = othItem;
vc5.title = @"其它";
vc5.view.backgroundColor = [UIColor lightGrayColor];
NSArray *viewControllers = @[homeNav,mesNav,sacNav,setNav,othNav];//把他们放在数组中
UITabBarController *tabBarController = [[UITabBarController alloc]init]; //初始化
tabBarController.delegate = self; //设置代理
[tabBarController setViewControllers:viewControllers animated:YES];
self.window.rootViewController = tabBarController;
return YES; //标志位(flag)
}
#pragma mark - TabBarController Delegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
NSLog(@"shouldSelectViewController");
return YES;
} //视图将要切换是调用,viewController为将要显示的控制器
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
NSLog(@"didSelectViewController");
//视图已经切换后调用,viewController 是已经显示的控制器
}