我正在尝试在使用UITabBarItem
的图片配置的某些UIImageRenderingModeAlwaysOriginal
上显示徽章。我这样做是因为期望的效果类似于凸起的UITabBarItem
a-la Instagram。这是我用来测试它的代码(它在UITabBarController
类别中):
- (void) replaceImageForTab:(int)itemIndex
defaultImage:(UIImage *)defaultImage
selectedImage:(UIImage *)selectedImage
title:(NSString *)title
{
NSArray *viewControllers = [self viewControllers];
UIViewController *vc = [viewControllers objectAtIndex:itemIndex];
[vc.tabBarItem setImage:[defaultImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[vc.tabBarItem setSelectedImage:[selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[vc.tabBarItem setTitle:title];
[vc.tabBarItem setBadgeValue:@"1"];
}
但是,徽章图像会被剪裁,如下所示:
我认为是因为徽章正在UITabBar
的{{1}}中添加,并且正在剪切其内容。但我无法修改该值,因为那是私有财产。我还有其他选择吗?
答案 0 :(得分:0)
我还没有办法改变库存徽章的偏移量,所以我不得不推出自己的解决方案。它不漂亮,但它有效(这也是UITabBarController
类别):
- (void) v_setBadgeValue:(NSString *)badgeValue inTab:(NSInteger)tabIndex
{
NSArray *viewControllers = [self viewControllers];
UIViewController *vc = [viewControllers objectAtIndex:tabIndex];
UITabBarItem *tabBarItem = vc.tabBarItem;
UIImage *normalImage = tabBarItem.image;
UIImage *selectedImage = tabBarItem.selectedImage;
UIImage *badgedNormalImage = [[self class] addBadgeWithValue:badgeValue toImage:normalImage];
UIImage *badgedSelectedImage = [[self class] addBadgeWithValue:badgeValue toImage:selectedImage];
[tabBarItem setImage:[badgedNormalImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[tabBarItem setSelectedImage:[badgedSelectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
}
+ (UIImage *) addBadgeWithValue:(NSString *)badgeValue toImage:(UIImage *)image
{
//Here you have to create your badge view. Let's just use a red square for now
UIView *badgeView = [[UIView alloc] initWithFrame:CGRectMake(16, 3, 14, 14)];
[badgeView setBackgroundColor:[UIColor redColor]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[imageView addSubview:badgeView];
UIGraphicsBeginImageContextWithOptions((imageView.bounds.size), NO, [[UIScreen mainScreen] scale]);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
现在你可以完全控制徽章的偏移量和位置,如果你和我一样有一个非常奇怪的UITabBar可以使用,这很重要。这是结果: