iOS开发之视图切换

2020-01-15 13:50:40王冬梅

  1. 创建一个UITabBarController对象
  2. 创建UITabBarController中每一个tab对应的要显示的对象viewController
  3. 通过UITabBarController的viewControllers属性将要显示的所有viewController添加到UITabBarController中
  4. 通过设置UITabBarController对象为window.rootViewController,然后显示window

 

复制代码
//a.初始化一个tabBar控制器
UITabBarController *tarbarVC = [[UITabBarController alloc] init];
//设置控制器为Window的根控制器
self.window.rootViewController = tarbarVC;
//b.创建子控制器
UIViewController *c1 = [[UIViewController alloc] init];
c1.view.backgroundColor = [UIColor grayColor];
c1.view.backgroundColor=[UIColor greenColor];
c1.tabBarItem.title = @"消息";
c1.tabBarItem.image = [UIImage imageNamed:@"tab_recent_nor"];
c1.tabBarItem.badgeValue = @"123";
UIViewController *c2 = [[UIViewController alloc] init];
c2.view.backgroundColor = [UIColor brownColor];
c2.tabBarItem.title = @"联系人";
c2.tabBarItem.image = [UIImage imageNamed:@"tab_buddy_nor"];
UIViewController *c3 = [[UIViewController alloc] init];
c3.tabBarItem.title = @"动态";
c3.tabBarItem.image = [UIImage imageNamed:@"tab_qworld_nor"];
UIViewController *c4 = [[UIViewController alloc] init];
c4.tabBarItem.title = @"设置";
c4.tabBarItem.image = [UIImage imageNamed:@"tab_me_nor"];
//c.添加子控制器到ITabBarController中
tarbarVC.viewControllers = @[c1,c2,c3,c4];
//d.设置Window为主窗口并显示出来
[self.window makeKeyAndVisible];

 

UITabBarControllerDelegate代理

 

复制代码
#pragma mark 该方法用于控制TabBarItem能不能选中
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController;

 

改变UITabBarController当前显示视图的方法

  1. 改变selectedIndex属性
  2. 改变selectedViewController属性