Search code examples
iosswiftuitabbarcontrollerios9uitabbaritem

(iOS 9 and below) How do you specify tab bar item text color during user interactions (both selected and normal state)


I need to know if there is a way to change the tab bar item title / text (not the image because it is working perfectly fine just by specifying tintColor) during actual user interaction? Like changing it's color when a certain button is tapped.

Currently the unselected / inactive tab bar item text has no color. Is there a way to specify it's color either through storyboard or code?

I know that the tab bar item title / text color can be specified using :

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .normal)

and

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .selected)

but this only applies if the the tab is not yet rendered. Calling the said methods after the tab bar controller gets created doesn't do anything. Please do note that my question is for iOS 9 and below since changing the tab bar tint color for selected and unselected is quite easy in iOS 10.


Solution

  • I got it. It turns out specifying attributes individually will work rather than globally.

    tabBar.items?[index].setTitleTextAttributes([NSForegroundColorAttributeName: normalColor], for: .normal)

    tabBar.items?[index].setTitleTextAttributes([NSForegroundColorAttributeName: selectedColor], for: .selected)