Friday, 6 May 2016

Change UITabBar item's image color and title text color

Some time there is a need to add tab bar in our app. Apple provide UITabBarController to add a tab bar . 
Here is an example to add tab bar in our app
To add  a tab bar  in our app, we create  a UITabBarController instance.

let tabVC  =  UITabBarController()

Then create  the view controller instances we want to add  in tab bar . For example , we create two UIViewController instance here. You can  create the subclasses of UIViewController as per your requirements.

let vc1 =  MyViewController1()
let vc2 = MyViewController2()


Then add  both view controller to tabVC 's viewControllers property as:

tabVC.viewControllers = [vc1, vc2]

Then set the index of the view controller we want to see selected by default as:

tabVC.selectedIndex = 1

Now we have set up tab bar controller and add two view controllers to it . Now we add the  tabBarItem property of both view controllers  like as:

vc1.tabBarItem   = UITabBarItem(title:"Profile", image:nil, tag:1)
 or 
vc1.tabBarItem  =  UITabBarItem(title:String, image:UIImage?, unSelectedImage:UIImage?)
 
Here title and image color are of system color that is light gray . We can change the image color for both selected and unselected state of UITabBar items as

vc1.tabBarItem  = UITabBarItem(title:"Profile", image:UIImage(named:"profile.png")?.imageWithRenderingMode(.AlwaysOriginal), tag: 1)

Then above code assign a title Profile for the vc1 tab and set a image to the tab. The title will appear at the bottom of the  tab image. The  tab image color will be now of the same color as profile.png(red, white whatever.)

But the title color is same as before. So to change the color of title also , add this line:

UITabBatItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Normal) 

This will change the color  of the title of the tab bar item  in tab bar to white for normal state. You can  change the title color for selected state also in same way , just change the state in above statement .

         

No comments:

Post a Comment