之前寫過一篇文章在任意UIView上顯示Badge,但IOS6上失敗了,原來是蘋果將Badge的類名改了,所以這裡作下兼容,源碼如下:
[plain]
- (UIView *)showBadgeValue:(NSString *)strBadgeValue
{
UITabBar *tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"" image:nil tag:0];
item.badgeValue = strBadgeValue;
NSArray *array = [[NSArray alloc] initWithObjects:item, nil];
tabBar.items = array;
[item release];
[array release];
//尋找
for (UIView *viewTab in tabBar.subviews) {
for (UIView *subview in viewTab.subviews) {
NSString *strClassName = [NSString stringWithUTF8String:object_getClassName(subview)];
if ([strClassName isEqualToString:@"UITabBarButtonBadge"] ||
[strClassName isEqualToString:@"_UIBadgeView"]) {
//從原視圖上移除
[subview removeFromSuperview];
//
[self addSubview:subview];
subview.frame = CGRectMake(self.frame.size.width-subview.frame.size.width, 0,
subview.frame.size.width, subview.frame.size.height);
[tabBar release];
return subview;
}
}
}
[tabBar release];
return nil;
}
- (void)removeBadgeValue
{
//
for (UIView *subview in self.subviews) {
NSString *strClassName = [NSString stringWithUTF8String:object_getClassName(subview)];
if ([strClassName isEqualToString:@"UITabBarButtonBadge"] ||
[strClassName isEqualToString:@"_UIBadgeView"]) {
[subview removeFromSuperview];
break;
}
}
}