自定义 UITabBar 未选中项的颜色

Posted

技术标签:

【中文标题】自定义 UITabBar 未选中项的颜色【英文标题】:Custom UITabBar unselected item's color 【发布时间】:2015-06-10 10:43:44 【问题描述】:

我正在尝试更改未选中的 UITabBarItems 的默认灰色。我设法更改了文本,但没有更改图像。

TabBar.appearance().barTintColor = UIColor(red: 86.0/255.0, green: 132.0/255.0, blue: 208.0/255.0, alpha: 1.0)

var normalTint: UIColor = UIColor.whiteColor()

TabBar.appearance().tintColor = UIColor.whiteColor()

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: normalTint,NSFontAttributeName: UIFont(name: "Arial", size: 13)!], forState: UIControlState.Normal)

【问题讨论】:

【参考方案1】:

ios 10 |斯威夫特 3

class TabBarVC: UITabBarController 

    override func viewDidLoad() 
        super.viewDidLoad()

        // make unselected icons white
        self.tabBar.unselectedItemTintColor = UIColor.white
    

【讨论】:

很好用。没有检查 iOS10 文档。【参考方案2】:

你可以使用.AlwaysOriginal

tabBarItem.selectedImage = UIImage(named: "first-selected")!.imageWithRenderingMode(.AlwaysOriginal)

【讨论】:

【参考方案3】: 如果您想通过 Storyboard 将未选中的图标设置为特定颜色。 您可以通过“用户定义的运行时属性”来完成,而无需添加代码。

【讨论】:

我在 iOS 9 中使用它并收到此错误:此类与键 unselectedItemTintColor 的键值编码不兼容。\【参考方案4】:

func styleTabBar()
    let fontAttributes = [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10.0)]
    let selectedFontAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10.0)]
    if #available(iOS 13.0, *) 
        let tabBarAppearance = UITabBarAppearance()
        let tabBarItemAppearance = UITabBarItemAppearance()
        tabBarItemAppearance.normal.iconColor = UIColor.gray
        tabBarItemAppearance.selected.iconColor = UIColor.red
        tabBarItemAppearance.normal.titleTextAttributes = fontAttributes
        tabBarItemAppearance.selected.titleTextAttributes = selectedFontAttributes
        
        tabBarAppearance.configureWithOpaqueBackground()
        tabBarAppearance.backgroundColor = UIColor.white
        tabBarAppearance.stackedLayoutAppearance = tabBarItemAppearance
        UITabBar.appearance().standardAppearance = tabBarAppearance
        if #available(iOS 15.0, *) 
            UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance
        
    else
        UITabBar.appearance().barTintColor = UIColor.white
        UITabBar.appearance().tintColor = UIColor.gray
        UITabBar.appearance().unselectedItemTintColor = UIColor.red
     UITabBarItem.appearance().setTitleTextAttributes(fontAttributes, for: .normal)
UITabBarItem.appearance().setTitleTextAttributes(selectedFontAttributes, for: .selected)
    

【讨论】:

以上是关于自定义 UITabBar 未选中项的颜色的主要内容,如果未能解决你的问题,请参考以下文章

iOS开发自定义UIPickView

如何在 NavigationView 中自定义项目背景和项目文本颜色?

自定义 iOS UINavigationBar/UITabBar 并移除 Tint Colors

Swift iOS UITabBar 自定义

Swift自定义UITabBar

Swift自定义UITabBar