UITabBarController是IOS总常用的ViewController之一,下面简单介绍一下其使用:
1.UITabBarController主要用于管理多个控制器
如上图tabBar的每一项对应一个viewController
2.根据提供的文档,UITabBarController通常作为整个程序的rootViewController,一般不建议添加到其他的 viewController中(之前将其添加到UINavigationController没什么问题,不过退出应用有时候调用生命周期函数有问题),使用一般如下:
self.window.rootViewController=tabController;//<pre name="code" class="html">tabController为自定义的UITabBarController
3.设置UITabBar的背景颜色:
[[UITabBar appearance] setBarTintColor:color];
self.tabBar.translucent=NO;//是否透明
4.设置UITabBarItem的字体颜色:
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:color,NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];//可以根据不同状态设置<pre name="code" class="html">UIControlStateSelected表明是选中后的状态的字颜色
5.设置UITabBarItem的图片和选中后的图片,和图片下面显示的文字:
[childVC.tabBarItem setImage:image];//正常情况显示图片
[childVC.tabBarItem setSelectedImage:selectedImage];//选中后显示的图片
[childVC.tabBarItem setTitle:title];//图片下面的文字
6.如果需要调整图片和文字之间的距离可以使用:
//设置字体的间距向上5pt
UIOffset titleOffset=UIOffsetMake(0, -5);
[childVC.tabBarItem setTitlePositionAdjustment:titleOffset];
7.在使用UITabBarController时候,一般是和UINavigationController结合使用,把UITabBarItem对应的controller放到一个UINavigationController中:
-(void)addChildVC:(UIViewController*)childVC title:(NSString*)title img:(NSString*)img selectedImg:(NSString*)selectedImg{
//childVC.title=title;
UIImage *image=[UIImage imageNamed:img];
UIImage *selectedImage=[UIImage imageNamed:selectedImg];
image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
selectedImage = [selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[childVC.tabBarItem setImage:image];
[childVC.tabBarItem setSelectedImage:selectedImage];
[childVC.tabBarItem setTitle:title];
//设置字体的间距向上5pt
UIOffset titleOffset=UIOffsetMake(0, -5);
[childVC.tabBarItem setTitlePositionAdjustment:titleOffset];
UINavigationController *navController=[[UINavigationController alloc]initWithRootViewController:childVC];//将<span style="font-family: Arial;">UITabBarItem对应的controller放到一个</span><span style="font-family: Arial;">UINavigationController中</span>
[self addChildViewController:navController];
//[_vcArray addObject:navController];
}
8.需要声明的是每个在UITabBarController中的viewController,UITabBarController都会为其增加一个tabBarItem属性,需要设置时,直接使用即可。
可以参考:
@interface UIViewController (UITabBarControllerItem)
@property(null_resettable, nonatomic, strong) UITabBarItem *tabBarItem; // Automatically created lazily with the view controller's title if it's not set explicitly.
@property(nullable, nonatomic, readonly, strong) UITabBarController *tabBarController; // If the view controller has a tab bar controller as its ancestor, return it. Returns nil otherwise.
@end
9.如果想用代码设置选中UITabBarItem可以使用:
self.selectedIndex=index;