如何以编程方式更改tabbarItem的图像 [英] how to programmatically change the tabbarItem's image
问题描述
我正在开发购物车"标签.最初,我只是使用默认的徽章值在底部标签栏上显示购物车中有多少物品.现在,设计师想花哨的时候,他想根据购物车中的物品数量来显示不同的图像.例如,如果有一个,则显示cartTab-1.png,如果有2,则显示cartTab-2.png ...
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...
我试图更改制表符( UITabBarItem
)的图像,但对我不起作用.可行吗我与同事讨论过,他说我可能必须自己在tabbarItem顶部绘制图像.你有什么建议吗?谢谢
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
更多详细信息:
- 我使用InterfaceBuilder创建了tabItem,然后在此处设置图像和标题
- 我需要支持ios4.所以我不能使用setSelectedImage ...
- 在我的情况下,这是KVO,如果购物车数量发生变化,它会通知更新图像的方法.不在初始化步骤中.
有人知道为什么 [self.tabBarItem setImage:[UIImage imageNamed:@"cartxxx.png"]]
不起作用吗?当我调试时,属性确实发生了变化,但用户界面保持不变
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
更新
以下代码有效.谢谢大家!
the below code works. Thanks everyone!
UIImage* cartTabImage = [UIImage imageNamed:cartTabImageName];
[[self.tabBarController.tabBar.items objectAtIndex:3] setImage:cartTabImage];
推荐答案
用于2个标签的Swift 3.0版本,
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)
这篇关于如何以编程方式更改tabbarItem的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!