Categories: Swift Programming

Rendering original color of UITabBarItems when an item is not selected with Swift

Greetings and Salutations!

By default in iOS, it changes the UITabBarItem(s) color to gray. You can only change the color of selected item and its background from Interface Builder.
So what you can do is, simply create icons of the color you want to see when items are not selected. Just render icon’s original color through code.
Confused? Let’s understand it with the following example.

I have these two PNG icons.

Now, I’m going to set these icons as TabBarItem images.

These were the results.

 

 

 

 

 

 

 

Let’s create a new Cocoa Touch Class sub class of UITabBarController.


Open your Storyboard and from Interface Builder set the UITabBarController to the Custom TabBar Class you just created.

In viewDidLoad of your Custom TabBar class.

for (var items = 0 ; items < tabBar.items!.count ; items++){
var tabItemIndex = tabBar.items![items] as! UITabBarItem
tabItemIndex.image = tabItemIndex.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
}

Run.

Add title to the items. Then again in your viewDidLoad of custom class.

//Makes the selected tabBarItem gray
tabBar.tintColor = UIColor.grayColor()
//Renders the Unselected title purple as of the icon
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(red: 121/255, green: 43/255, blue: 157/255, alpha: 1)], forState:.Normal)
//Renders the selected title same as tint Color UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.grayColor()], forState:UIControlState.Selected)


After running again.

 

 

 

 

 

 

 

 

 

 

 

Here is the link to the sample project on Github.
So Long!

Aaqib Hussain

Recent Posts

Things to know when moving to Germany

This article covers some important things you must know when you are considering a move…

3 years ago

Unit Testing in Android for Dummies

What is Unit Testing? In its simplest term, unit testing is testing a small piece…

4 years ago

Factory Design Pattern

In this article, you will learn about a type of Creational Design Pattern which is…

5 years ago

Creating Target specific Theme in iOS

In this tutorial, you will go through the use of targets to achieve two separate…

5 years ago

Facade Design Pattern

In this article, you will learn about a type of Structural Design Pattern which is…

5 years ago

Singleton Design Pattern

In this article you will learn about a type of Creational Design Pattern which is…

5 years ago