设置UITabBarItem上title颜色(适配iOS 13)

最近升级了iOS13系统,之前项目使用系统TabBarController创建的项目在启动的时候selectTitleColorNormalTitleColor 有时候设置不起作用。
tabBarItem选中颜色有时为设置的颜色,有时变为系统蓝色;
tabBarItem未选中颜色有时为设置的颜色,有时变为系统蓝色;

适配如下:

if (@available(iOS 13.0, *)) {
    // iOS 13以上
    self.tabBar.tintColor = [UIColor F2400BRedColor];
    self.tabBar.unselectedItemTintColor = [UIColor grayColor];
    UITabBarItem *item = [UITabBarItem appearance];
    [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} forState:UIControlStateNormal];
    [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} forState:UIControlStateSelected];
} else {
    // iOS 13以下
    UITabBarItem *item = [UITabBarItem appearance];
    [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12], NSForegroundColorAttributeName:[UIColor grayColor]} forState:UIControlStateNormal];
    [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12], NSForegroundColorAttributeName:[UIColor F2400BRedColor]} forState:UIControlStateSelected];
}

查找资料过程中,发现还有以下设置也会起作用:
感谢博主「幻灬听」分享
原文链接:请点这里

Apple将设置UITabBarItem的文字属性的任务,交给了13中新添加的属性UITabBarItem.standardAppearance。代码如下:

viewController.tabBarItem.title = title;
if (@available(iOS 13.0, *)) {
    UITabBarAppearance *appearance = [UITabBarAppearance new];
    // 设置未被选中的颜色
    appearance.stackedLayoutAppearance.normal.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
    // 设置被选中时的颜色
    appearance.stackedLayoutAppearance.selected.titleTextAttributes = @{NSForegroundColorAttributeName: :[UIColor F2400BRedColor]};
    
    viewController.tabBarItem.standardAppearance = appearance;
} else {
    [viewController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor grayColor]}];
}

以上内容仅做为我自己的学习及收藏内容,如有不对请指出,Thanks♪(・ω・)ノ~

你可能感兴趣的:(设置UITabBarItem上title颜色(适配iOS 13))