给tabBar设置图片和字体颜色的几种方法

  • 如今非常多应用都使用到了tabBar,我们往往在给tabBar设置图片和字体的时候,当选中状态下,往往字体的颜色和图片的颜色不匹配,有时候就显得无从下手。我也经常忘了,全部写这个博客的目的,相当于给自己做个笔记,也希望给有须要的朋友们一点帮助。

  • 写了个小demo,来演示这个问题:

 - (void)viewDidLoad {
    [super viewDidLoad];

    ZYGroupBuyViewController *group = [[ZYGroupBuyViewController alloc]init];
    [self createVC:group Title:@"团购" imageName:@"icon_tabbar_homepage"];

    ZYVisitTableViewController *visit = [[ZYVisitTableViewController alloc]init];
    [self createVC:visit Title:@"上门" imageName:@"icon_tabbar_onsite"];

    ZYBusinessViewController *business = [[ZYBusinessViewController alloc]init];
    [self createVC:business Title:@"商家" imageName:@"icon_tabbar_merchant"];

    ZYProfileViewController *profile = [[ZYProfileViewController alloc]init];
    [self createVC:profile Title:@"我的" imageName:@"icon_tabbar_mine"];

    ZYMoreViewController *more = [[ZYMoreViewController alloc]init];
    [self createVC:more Title:@"很多其它" imageName:@"icon_tabbar_misc"];

}
  • 这里我习惯封装一个方法出来,方便别的地方调用:
 - (void)createVC:(UIViewController *)vc Title:(NSString *)title imageName:(NSString *)imageName
{
    vc.title = title;

    self.tabBar.tintColor = [UIColor colorWithRed:68/255.0 green:173/255.0 blue:159/255.0 alpha:1];
    vc.tabBarItem.image = [UIImage imageNamed:imageName];
    NSString *imageSelect = [NSString stringWithFormat:@"%@_selected",imageName];
    vc.tabBarItem.selectedImage = [[UIImage imageNamed:imageSelect] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self addChildViewController:[[UINavigationController alloc]initWithRootViewController:vc]];
}
  • 那总结一下:
    • 第一种方法:
    // 68 173 159
  [vc.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:68/255.0 green:173/255.0 blue:159/255.0 alpha:1]} forState:UIControlStateSelected];
  • 另外一种方法
self.tabBar.tintColor = [UIColor colorWithRed:68/255.0 green:173/255.0 blue:159/255.0 alpha:1];

注意一点:

 vc.title = title;

这是相当于:
同一时候设置tabbar和navigationBar的文字
tabBar

原文地址:https://www.cnblogs.com/lxjshuju/p/7209542.html