Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to programmatically change the tabbarItem's image

Tags:

ios

uitabbar

I'm developing a shopping cart tab. Originally I just use the default badge value to show how many items in the cart on the bottom tabbar. Now the designer wants to be fancy, he wants to show different image based on how many items in the cart. For example, if there's one, show cartTab-1.png, if 2, show cartTab-2.png...

I tried to change the tabaritem (UITabBarItem)'s image but it didn't work for me. Is it feasible? I discussed with my colleague, he said I may have to draw the image on top of the tabbarItem by myself. Do you have any suggestion? Thanks

more details:

  1. I created the tabItem using InterfaceBuilder, and set the image and title over there
  2. I need to support ios4. So I can't use the setSelectedImage...
  3. In my case it's a KVO, if the cart count changes, it notifies the method to update the image. not in the initialize step.

does anyone know why [self.tabBarItem setImage:[UIImage imageNamed:@"cartxxx.png"]] doesn't work? When I debug, the property do changed, but the UI remains same

Update

the below code works. Thanks everyone!

UIImage* cartTabImage = [UIImage imageNamed:cartTabImageName];
[[self.tabBarController.tabBar.items objectAtIndex:3] setImage:cartTabImage];
like image 306
Jason S Avatar asked Nov 29 '22 15:11

Jason S


1 Answers

Swift 3.0 version for 2 tabs,

self.tabBar.items?[0].image = UIImage(named: "inactive_image_0")?.withRenderingMode(.alwaysOriginal)
self.tabBar.items?[0].selectedImage = UIImage(named: "active_image_0")?.withRenderingMode(.alwaysOriginal)

self.tabBar.items?[1].image = UIImage(named: "inactive_image_1")?.withRenderingMode(.alwaysOriginal)
self.tabBar.items?[1].selectedImage = UIImage(named: "active_image_1")?.withRenderingMode(.alwaysOriginal)
like image 156
Engnyl Avatar answered Dec 09 '22 15:12

Engnyl