[iOS 13] UITabBarItem 標(biāo)題顏色設(shè)置無(wú)效問(wèn)題

使用新版XcodeVersion 11.2.1 (11B500)創(chuàng)建項(xiàng)目時(shí),發(fā)現(xiàn)對(duì)UITabController的UITabBarItem中的字體顏色設(shè)置無(wú)法生效
原來(lái)的寫(xiě)法:

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)過(guò)Google和查看官方文檔,在iOS 13中,Apple將設(shè)置UITabBarItem的文字屬性的任務(wù),交給了13中新添加的屬性UITabBarItem.standardAppearance

下面是適配iOS 13的寫(xiě)法:

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
            }
        }
    }
}
以上代碼均在UITabBarController子類TabBarViewControllerviewDidLoad中設(shè)定
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。