自定义 UITabBar 未选中项的颜色

Custom UITabBar unselected item's color

我正在尝试更改未选中的 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)

可以使用 .AlwaysOriginal

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

iOS 10 | Swift 3

class TabBarVC: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // make unselected icons white
        self.tabBar.unselectedItemTintColor = UIColor.white
    }
}
  • 如果想通过 Storyboard 将未选中的图标设置为特定颜色。
  • 您可以通过 'User defined runtime attributes' 完成,无需添加代码。

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)
    }

}