Kyle Banks

iOS: Customizing Selected/Unselected UITabBarItem Images in a UITabBarController

Written by @kylewbanks on Apr 4, 2013.

Like so many of the iOS UI components, the UITabBarItem is very easy to customize and manipulate. This post will show you how to add some basic customization to your tab bar, by defining custom images for each tab based on the state of the tab. By default, a blue tint is applied to the selected tab, but we can go further than that by completely changing the image, or applying our own tint to it.

In your UITabBarController, add the following to the viewDidLoad method:

- (void)viewDidLoad 
{
    [super viewDidLoad];

    //Iterate through the tabs and set the on/off images
    for(UITabBarItem *tbItem in [[self tabBar] items])
    {
        [tabBarItems addObject:tbItem];
        [tbItem setFinishedSelectedImage:[self imageForTabBarItem:[tbItem tag] selected:YES]
             withFinishedUnselectedImage:[self imageForTabBarItem:[tbItem tag] selected:NO]];
    }
}

Next, create the following method to determine which image is appropriate based on the tab index and the selected state of the tab:

- (UIImage *)imageForTabBarItem:(int)tab selected:(BOOL)selected
{
    NSString *imageName;
    switch(tab)
    {
        case 0:
            imageName = [NSString stringWithFormat:@"nav_one_%@.png", selected ? @"on":@"off"];
            break;
        case 1:
            imageName = [NSString stringWithFormat:@"nav_two_%@.png", selected ? @"on":@"off"];
            break;
        case 2:
            imageName = [NSString stringWithFormat:@"nav_three_%@.png", selected ? @"on":@"off"];
            break;
    }
    return [UIImage imageNamed:imageName];
}

Each of your image names will have to conform to a simple standard in order for this to work. The off, or unselected, image will be named image_name_off.png, while the on, or selected, image will have the same name except with an 'on' suffix, like image_name_on.png.

Let me know if this post was helpful on Twitter @kylewbanks or down below!