美文网首页
[iOS 13] UITabBarItem 标题颜色设置无效问题

[iOS 13] UITabBarItem 标题颜色设置无效问题

作者: 汴城码农 | 来源:发表于2019-12-18 18:41 被阅读0次

    使用新版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
                }
            }
        }
    }
    
    以上代码均在UITabBarController子类TabBarViewControllerviewDidLoad中设定

    相关文章

      网友评论

          本文标题:[iOS 13] UITabBarItem 标题颜色设置无效问题

          本文链接:https://www.haomeiwen.com/subject/kngunctx.html