Sunday, May 22, 2011

UITabBarController with custom UITabBarItem colors


In the last few days my team and I were tasked with creating an app for a brand which has orange colors. We wanted a tab bar. We wanted the selected tab bar item to highlight in orange rather than the default aqua color. If you're reading this than you probably already know that a straightforward way to achieving this using UITabBarController doesn't exist. In this post I'd like to go through the code I've written for a custom tab bar controller that allows you to set custom image masks for your highlighted items. The project hasn't been implemented to fully replicate the functionality of UITabBarController, however the basics are in and you can add additional features if you like.


What does the project consist of?


The project consists of 3 classes as shown below.


How do you use it?


Very simple. You use it just like you would use UITabBarController with two exceptions:

  1. If you're loading your current tab bar controller from a NIB file you will need to set it up programatically.
  2. You need to set up the image masks used for selected and unselected items.

So where do you start? Download the project code here. Copy the files from the TATabBarController folder into your project and change all references of UITabBarController to TATabBarController. Once you've done that you're left with going through 4 easy steps to get things up and running.



Don't forget to set the tabBarItem property for the view controllers you're adding to the tab bar controller - otherwise nothing will appear.


How does it work?


Once you set the view controllers the magic begins to happen. Below I'll describe how I went about drawing the tab bar images and text. The rest of the details regarding the functioning of the tab bar will be left out of the scope of this post. The code that shows how all this is done is located in TATabBars - (UIImage*)_tabBarImage:(UIImage*)tabBarImage withGradient:(UIImage*)gradientImage method.



Additionally, if we are drawing the selected tab bar item we apply a shadow to the image and text.


You can download the project code here. Have fun!