Charlie
Charlie

Reputation: 43

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.

Upvotes: 0

Views: 2346

Answers (2)

Tipu
Tipu

Reputation: 55

just add this line in your runtime attribute keypath

for selecetd --> tintColor for not selected --> unselectedItemTintColor

Upvotes: 0

iDeveloper
iDeveloper

Reputation: 2444

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
 }

Here is the output

Upvotes: 7

Related Questions