的iOS标签栏自定义项目图像,标签栏左侧
问题描述:
我试图改变标签栏项目图像的颜色绘制灰度图像,这个我使用下面的代码:的iOS标签栏自定义项目图像,标签栏左侧
// Generate a tinted unselected image based on image passed via the storyboard.
for (UIViewController *vc in tabBarController.viewControllers) {
UITabBarItem *item = vc.tabBarItem;
UIImage *image = item.image;
UIImage *imageSel = [image imageWithColor:selectedColor];
UIImage *imageUnsel = [image imageWithColor:unselectedColor];
// Next is not working to set unselected image!
// But setFinishedSelectedImage does.
//item.selectedImage = imageSel;
item.image = imageSel;
//[item setFinishedSelectedImage:imageSel withFinishedUnselectedImage:imageUnsel];
}
UITabBarItem *item = tabBarController.moreNavigationController.tabBarItem;
UIImage *image = [UIImage imageNamed:@"menu-more"];
UIImage *imageSel = [image imageWithColor:selectedColor];
UIImage *imageUnsel = [image imageWithColor:unselectedColor];
item.image = imageSel;
// [item setFinishedSelectedImage:imageSel withFinishedUnselectedImage:imageUnsel];
imageWithColor:是的UIImage扩展使用原始图像的alpha值生成具有颜色的图像。
代码首次执行,一切都很好。
更改颜色(调用上面的代码)后,所有标签栏项目都显示在标签栏左侧的文本中。在模拟器和设备(iPhone + iPad)中都会发生。这是一个错误?
答
那么我想出了修复。而不是设置UITabBarItem的形象,你需要从头创建UITabBarItem并设置图像出现,就像这样:
for (UIViewController *vc in tabBarController.viewControllers) {
UITabBarItem *newItem = [[UITabBarItem alloc] initWithTitle:someTitle image:someImageUnsel selectedImage:someImageSel];
vc.tabBarItem = newItem;
}
UITabBarItem *newItem = [[UITabBarItem alloc] initWithTitle:someTitle image:someImageUnsel selectedImage:someImageSel];
tabBarController.moreNavigationController.tabBarItem = newItem;
有这种解决方案虽然一个问题:设置它的tabBarItem后MoreNavigationController会弹回。普通苹果,wtf ?!
如果有人可以提供更好的解决方案,请做...
答
您可以设置图像用故事板本身tabbaritem。要将颜色更改为选定的tabbaritem,无需为循环编写任何代码。您可以使用下面的行。
[[UITabBar appearance] setTintColor:[UIColor greenColor]];
这只会改变所选项目的颜色,但未选中的项目将显示为灰色。已经尝试过。 – Borzh
我可以知道你使用tabbaritem图像的选定和未选择的颜色。 – Rajesh
是的,两者,实际上未选中的颜色与选定的颜色相同,但只有0.5的alpha。 – Borzh