UITabBarController
1.介绍
- UITabBarController的使用步骤
- 初始化UITabBarController
- 设置UIWindow的rootViewController为UITabBarController
根据具体情况,通过addChildViewController方法添加对应个数的子控制器
注意:先添加的在前面
- UITabBarController的子控制器
• UITabBarController添加控制器的方式有2种
i. 添加单个子控制器
- (void)addChildViewController:(UIViewController *)childController;
ii. 设置子控制器数组
@property(nonatomic,copy) NSArray *viewControllers;
- UITabBar
• 如果UITabBarController有N个子控制器,那么UITabBar内部就会有N个UITabBarButton作为子控件
例如UITabBarController有4个子控制器,UITabBar的结构大致如下: - UITabBarButton
UITabBarButton里面显示什么内容,由对应子控制器的tabBarItem属性决定
UITabBarController工作原理
UITabBarController的view结构
UITabBarController工作原理
遍历tabbar所有子控制器
/**
1.在选项卡应用中 self.parentViewController = self.tabBarController
2.可以根据self.tabBarItem设置其中的属性
3.遍历tabbar的所有子视图控制器,根据对应的视图控制器去设置
4.self.tabBarController.viewControllers获得视图容器直接对子视图进行操作
**/
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%@ %@", self.parentViewController, self.tabBarController);
NSLog(@"%@", self.tabBarController.viewControllers);
for (UIViewController *controller in self.tabBarController.viewControllers) {
// 判断是否是第二个视图控制器
if ([controller isKindOfClass:[SecondViewController class]]) {
[controller.view setBackgroundColor:[UIColor greenColor]];
} else if ([controller isKindOfClass:[ThirdViewController class]]) {
[controller.view setBackgroundColor:[UIColor redColor]];
}
}
SecondViewController *second = self.tabBarController.viewControllers.lastObject;
[second.view setBackgroundColor:[UIColor greenColor]];
[self.tabBarItem setTitle:@"第一项"];
[self.tabBarItem setBadgeValue:@"10"];
[self.tabBarItem setImage:[UIImage imageNamed:@"tab1.png"]];
}
用代码对tabbarControl进行操作
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
// 初始化两个视图控制器
// 1. 实例化tabbar视图控制器
// 2. 设置tabbar内容
// 3. 将tabbar设置为window的根视图控制器
MainViewController *controller = [[MainViewController alloc]init];
[controller.tabBarItem setTitle:@"第一项"];
SecondViewController *second = [[SecondViewController alloc]init];
[second.tabBarItem setTitle:@"结账"];
UITabBarController *tab = [[UITabBarController alloc]init];
tab.viewControllers = @[controller, second];
[self.window setRootViewController:tab];
[self.window makeKeyAndVisible];
return YES;
}