[iOS 13] UITabBarItem 标题字体显示错误及返回变蓝色的问题

有一个一年多没动过需求的app要改,打开一看竟然有一个bug。tabbar 标题字体返回变成蓝色,找了多个系统版本比对发现是ios13开始出现的问题
在iOS 13中,Apple将设置UITabBarItem的文字属性的任务,交给了13中新添加的属性UITabBarItem.standardAppearance。
UITabBarAppearance和UIBarAppearance的官方文档:

UITabBarAppearance
Overview
After creating a UITabBarAppearance object, use the methods and properties of this class to specify the appearance of items in the tab bar. Use the inherited properties from UIBarAppearance to configure the background and shadow attributes of the tab bar itself.

UIBarAppearance
Overview
A UIBarAppearance object contains the common traits shared by navigation bars, tab bars, and toolbars. When configuring a specific type of bar, you usually instantiate the appropriate bar appearance subclass. However, you may also create a UIBarAppearance object, configure its properties, and use it to create new bar appearance objects in your app.

文档中说明了,在创建一个对象后,设置的对象属性时,就需要初始化并设置一个UIBarAppearance或其子类来改变该对象的外观属性。然而,文档中并没有说明,在何时设置UIBarAppearance无效。

推测,UIBarAppearance的属性只会在某一阶段被读取,过了这个阶段后,即使多次修改UIBarAppearance的属性,也不会使最终的界面显示效果发生变化。

适配ios13
if (@available(iOS 13.0, *)) {
    UITabBarAppearance *appearance = [UITabBarAppearance new];
    // 设置未被选中的颜色
   appearance.stackedLayoutAppearance.normal.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
    // 设置被选中时的颜色
    
    appearance.stackedLayoutAppearance.selected.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor redColor]};
  
  
 viewController.tabBarItem.standardAppearance = appearance;
} else {
    [viewController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} forState:UIControlStateSelected];
}
   //也可以这么搞
if (@available(iOS 13.0, *)) {                 
    [[UITabBar appearance] setUnselectedItemTintColor:Color_666666];
}
其实我这么设置了一下也行了,就设置了一个背景色用[item setTitleTextAttributes:selectAtts forState:UIControlStateSelected];这个方法也可以正常显示
+ (void)initialize {
//    [[UITabBar appearance] setTranslucent:NO];
    // 设置背景颜色
    [UITabBar appearance].barTintColor = [UIColor colorWithRed:0.97f green:0.97f blue:0.97f alpha:1.00f];
}

你可能感兴趣的:([iOS 13] UITabBarItem 标题字体显示错误及返回变蓝色的问题)