+ (void)initialize {
UIFont *textFont = [UIFont systemFontOfSize:12];
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = textFont;
attrs[NSForegroundColorAttributeName] = TextColor;
NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
selectedAttrs[NSFontAttributeName] = textFont;
selectedAttrs[NSForegroundColorAttributeName] = BtnColor;
if (@available(iOS 13.0,*)) {
UITabBarAppearance *appearance = [UITabBarAppearance new];
appearance.stackedLayoutAppearance.normal.titleTextAttributes = attrs;
appearance.stackedLayoutAppearance.selected.titleTextAttributes = selectedAttrs;
appearance.backgroundImage = [UIImage imageWithColor:[UIColor clearColor]];
appearance.shadowImage = [UIImage imageWithColor:[UIColor clearColor]];
// 官方文档写的是 重置背景和阴影为透明
[appearance configureWithTransparentBackground];
UITabBar.appearance.standardAppearance = appearance;
}else{
UITabBarItem *item = [UITabBarItem appearance];
[item setTitleTextAttributes:attrs forState:UIControlStateNormal];
[item setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
UITabBar.appearance.backgroundImage = [UIImage new];
UITabBar.appearance.shadowImage = [UIImage new];
}
}
// 通过颜色生成图片
+ (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
值得注意的是,在iOS13以上,UITabBar文字背景设置是由UITabBar的UITabBarAppearance属性去设置。