使用新版XcodeVersion 11.2.1 (11B500)
創(chuàng)建項目時,發(fā)現(xiàn)對UITabController的UITabBarItem中的字體顏色設(shè)置無法生效
原來的寫法:
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];
經(jīng)過Google和查看官方文檔,在iOS 13
中,Apple將設(shè)置UITabBarItem的文字屬性的任務(wù),交給了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
}
}
}
}