Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change UITabBarItem Un-selected Color Tint - Swift

Quite simply, I would like to be able to change the colouring of the un-selected items in my tab bar.

See below the "Most Viewed" Object barley readable in default colour.

Here is code I have tried to implement:

UITabBarItem.appearance().setTitleTextAttributes(NSDictionary(object: UIColor.greenColor(), forKey: NSFontAttributeName), forState: UIControlState.Normal)

enter image description here

However, using this code doesn't work. Does anyone know how to achieve this effect specially in swift?


like image 536
Ryan Avatar asked Sep 13 '14 17:09

Ryan


2 Answers

From UITabBarItem class docs:

By default, the actual unselected and selected images are automatically created from the alpha values in the source images. To prevent system coloring, provide images with UIImageRenderingModeAlwaysOriginal.

The clue is not whether you use UIImageRenderingModeAlwaysOriginal, the important thing is when to use it.

To prevent the grey color for unselected items, you will just need to prevent the system colouring for the unselected image. Here is how to do this:

var firstViewController:UIViewController = UIViewController()
// The following statement is what you need
var customTabBarItem:UITabBarItem = UITabBarItem(title: nil, image: UIImage(named: "YOUR_IMAGE_NAME")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), selectedImage: UIImage(named: "YOUR_IMAGE_NAME"))
firstViewController.tabBarItem = customTabBarItem

As you can see, I asked iOS to apply the original color (white, yellow, red, whatever) of the image ONLY for the UNSELECTED state, and leave the image as it is for the SELECTED state.

Also, you may need to add a tint color for the tab bar in order to apply a different color for the SELECTED state (instead of the default iOS blue color). As per your screenshot above, you are applying white color for the selected state:

self.tabBar.tintColor = UIColor.whiteColor()
like image 81
Malloc Avatar answered Sep 22 '22 06:09

Malloc


Swift 4 :

You can use unselectedItemTintColor of UITabBar. Note that it changes all unselected icons tint color.

Usage :

myTabBar.unselectedItemTintColor = .black
like image 32
Skaal Avatar answered Sep 22 '22 06:09

Skaal