使用新版XcodeVersion 11.2.1 (11B500)
创建项目时,发现对UITabController的UITabBarItem中的字体颜色设置无法生效
原来的写法:
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.red], for: UIControl.State.normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.blue], for: UIControl.State.selected)
或者
if #available(iOS 13.0, *) {
let array = self.tabBar.items
for item:UITabBarItem in array! {
item.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.red], for: UIControl.State.selected)
item.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.orange], for: UIControl.State.normal)
}
}
OC版
[[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:RGB_COLOR(82, 82, 82, 1)} forState:UIControlStateNormal];
[[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:Main_Dominant_Pass_Color} forState:UIControlStateSelected];
经过Google和查看官方文档,在iOS 13
中,Apple将设置UITabBarItem的文字属性的任务,交给了13中新添加的属性UITabBarItem.standardAppearance
下面是适配iOS 13的写法:
class TabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.red], for: UIControl.State.normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.blue], for: UIControl.State.selected)
if #available(iOS 13.0, *) {
let array = self.tabBar.items
for item:UITabBarItem in array! {
item.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.red], for: UIControl.State.selected)
item.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.orange], for: UIControl.State.normal)
let uitabApp:UITabBarAppearance = UITabBarAppearance()
uitabApp.stackedLayoutAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.cyan]
uitabApp.stackedLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.orange]
item.standardAppearance = uitabApp
}
}
}
}
网友评论