简体   繁体   中英

How do I Set Unselected Tab Bar Item Color using Swift in Xcode with an iOS 15+ Device?

I'm trying to customize a UITabBar using Swift in Xcode, however I can't figure our how to set the color of the unselected items using the menu on the right side of the window. I've tried the following approaches:

  1. I made a custom class for the TabBarController and implemented it as follows:
class CustomTabBarController : UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // set unselectedItemTintColor for UITabBar contained in this Controller...
        self.tabBar.unselectedItemTintColor = UIColor.white
    }
}
  1. When method 1 didn't work, I updated the custom class for the TabBarController with the following implementation...
class CustomTabBarController : UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // try setting unselected item tint color using new Appearance API...
        let appearance = UITabBarAppearance()
        
        appearance.backgroundColor = UIColor.white
        appearance.shadowImage = UIImage()
        appearance.shadowColor = UIColor.white

        appearance.stackedLayoutAppearance.normal.iconColor = UIColor.white
        appearance.stackedLayoutAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
        appearance.stackedLayoutAppearance.normal.badgeBackgroundColor = UIColor.white

        self.tabBar.standardAppearance = appearance
    }
}

Neither of these implemented approaches worked, so I'm trying to figure out what approach/implementation will work. I'm using Xcode version 13.2.1 and Swift version 5.5.2 on an iPhone 11 Pro Max device emulator running iOS 15.2.

Thank you in advance. I really appreciate any suggestions I could get for solving this issue.

I just face the same problem and find a solution for this.

Put this code in your UITabBarController class

if #available(iOS 15, *) {
           let tabBarAppearance = UITabBarAppearance()
            tabBarAppearance.backgroundColor = .white
            tabBarAppearance.stackedLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: UIColor.red]
            tabBarAppearance.stackedLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.black]
            tabBarAppearance.stackedLayoutAppearance.normal.iconColor = UIColor.black
            tabBarAppearance.stackedLayoutAppearance.selected.iconColor = UIColor.red
            tabBarView.standardAppearance = tabBarAppearance
            tabBarView.scrollEdgeAppearance = tabBarAppearance
 }

这是输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM