iOS sets tabbar unselected status text color

Original code

- (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];
    }
}

I encountered a problem, that is, setting the unselected text color of the tabar in iOS did not work.

Core function code stackedLayoutAppearance.normal.titleTextAttributes

Just add the following code

    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;
    }

Guess you like

Origin blog.csdn.net/LIUXIAOXIAOBO/article/details/131253869