Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change UITabBar image dynamically in iOS

At some point during runtime, I want to change the image for one of the tabs in my UITabBar. Here is what I have tried so far:

[[self.tabBarController.tabBar.items objectAtIndex:1]
    setImage:[UIImage imageNamed:@"image-name"]
    forState:UIControlStateNormal];

The above gives me a -[UITabBarItem setImage:forState:]: unrecognized selector sent to instance

If I use the setImage method without forState it works, but this method was deprecated in iOS 3.

I tried your answers, but now there's this weird blue line above the UITabBar's UIIMage I changed. Any idea why?

enter image description here

like image 840
thisiscrazy4 Avatar asked Feb 13 '23 02:02

thisiscrazy4


1 Answers

Use image and selectedImage properties:

UITabBarItem *item = [self.tabBarController.tabBar.items objectAtIndex:1];
item.image = [UIImage imageNamed:@"image"];
item.selectedImage = [UIImage imageNamed:@"selected_image"];

Also pay attention on this:

By default, the actual selected image is automatically created from the alpha values in the source image. To prevent system coloring, provide images with UIImageRenderingModeAlwaysOriginal.

like image 183
Vlad Papko Avatar answered Feb 23 '23 22:02

Vlad Papko