iOS 设置tabbar 未选中状态文字颜色

文章描述了在iOS应用中遇到的一个问题,即在某些版本中设置TabBar未选中文字颜色无效。解决方案涉及到使用`UITabBarAppearance`,特别是`stackedLayoutAppearance.normal.titleTextAttributes`来设置未选中状态的文字属性。同时,文章提到了`TPSkinManager`用于颜色匹配,并提供了兼容iOS13.0及更高版本的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原有代码

- (void)setUpOneViewController :(UIViewController *)Vc WithImage:(UIImage *)image WithSelImage:(UIImage *)selImage WithTitle:(NSString *)title{
    
    Vc.tabBarItem.image = image;
    Vc.tabBarItem.selectedImage = selImage;
    Vc.tabBarItem.title = title;
    
    //正常
    NSMutableDictionary *normalDict = [NSMutableDictionary dictionary];
    normalDict[NSFontAttributeName] = appFont(10*PLUS_SCALE, NO);
    normalDict[NSForegroundColorAttributeName] = [[TPSkinManager shareManager]colorAutoMatch:TPSkinMapKey_tabBar_titleNormalColor];
    [Vc.tabBarItem setTitleTextAttributes:normalDict forState:UIControlStateNormal];
    //选中
    NSMutableDictionary *selectedDict = [NSMutableDictionary dictionary];
    selectedDict[NSForegroundColorAttributeName] =  [[TPSkinManager shareManager]colorAutoMatch:TPSkinMapKey_tabBar_titleSelectedColor];
    [Vc.tabBarItem setTitleTextAttributes:selectedDict forState:UIControlStateSelected];
    self.tabBar.tintColor = [[TPSkinManager shareManager]colorAutoMatch:TPSkinMapKey_tabBar_titleSelectedColor];
    if (@available(iOS 13.0, *)) {
        /*ios 13 及以上的时候,
         1 如果 setTitleTextAttributes 中没有设置字体颜色
         这里设置的字体颜色就会有其作用,
         2 如果 setTitleTextAttributes 有设置字体颜色,必须给 self.tabBar.unselectedItemTintColor 设置一个
         颜色,未选中字颜色才会起作用(但这里起作用的颜色是setTitleTextAttributes),否则会展示一个系统默认的灰色字体;
        */
        /*
         ios 13 以前的只需要设置 setTitleTextAttributes 即可设置字体颜色
         */
        self.tabBar.unselectedItemTintColor = [[TPSkinManager shareManager]colorAutoMatch:TPSkinMapKey_tabBar_titleNormalColor];
    }
}

遇到一个问题,就是iOS设置 tabar 未选中的文字颜色,没有起作用

核心功能代码 stackedLayoutAppearance.normal.titleTextAttributes

将下面的代码补充下就可以了

    if (@available(iOS 15.0, *)) {
        UITabBarAppearance * appearance = [[UITabBarAppearance alloc] init];
        // 背景色
        appearance.backgroundColor = BackGroundColor;
        NSDictionary *dic = @{NSFontAttributeName:appFont(10*PLUS_SCALE, NO)};
        NSDictionary *normalItemStyleDic = @{NSFontAttributeName:appFont(10*PLUS_SCALE, NO), NSForegroundColorAttributeName:[[TPSkinManager shareManager]colorAutoMatch:TPSkinMapKey_tabBar_titleNormalColor]};
        appearance.stackedLayoutAppearance.selected.titleTextAttributes = dic; // 设置选中attributes
        appearance.stackedLayoutAppearance.normal.titleTextAttributes = normalItemStyleDic;
        self.tabBar.standardAppearance = appearance;
        self.tabBar.scrollEdgeAppearance = appearance;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值