Search code examples
iosif-statementuitabbaritemnsindexpath

iOS - Simple way to check which UITabBar option is selected


My objective is to make an if/else statement so that I can say: if a TabBarItem is selected, setSelectedImageTintColor to this color.

I am new to ObjC and not exactly sure how to implement the if statement. Here is my viewDidLoad:

- (void)viewDidLoad
{
[super viewDidLoad];

UITabBarItem *item0 = [self.tabBar.items objectAtIndex:0];
item0.image = [[UIImage imageNamed:@"red.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];


UITabBarItem *item1 = [self.tabBar.items objectAtIndex:1];
item1.image = [[UIImage imageNamed:@"yellow.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

UITabBarItem *item2 = [self.tabBar.items objectAtIndex:2];
item2.image = [[UIImage imageNamed:@"green.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

UITabBarItem *item3 = [self.tabBar.items objectAtIndex:3];
item3.image = [[UIImage imageNamed:@"black.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

[[UITabBar appearance] setSelectionIndicatorImage:
 [UIImage imageNamed:@"item.png"]];


}

As you can see I have a separate image specified for each of the TabBarItems, and I would like to make the highlight color match the image (so a red highlight for red.png, a yellow for yellow.png, etc)

How can I implement this if/else statement? Again, I'd like to check for the indexPath (0-3) and then set a custom setSelectedImageTintColor for the tabBarItem. Another option for me would be to remove the highlight altogether, if this would be more practical.


Solution

  • You should implement the UITabBarDelegate protocol into your ViewController, and set the UITabBar delegate to self

    self.tabBar.delegate = self;
    

    After that, you can implement the method tabBar:didSelectItem:

    - (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
    {
        // Check here for the item and change tintColor accordingly
        // For example:
        if([item isEqual:[self.tabBar.items objectAtIndex:1]) {
            tabBar.selectedImageTintColor = [UIColor redColor];
        }
    }