在任意UIView上显示Badge(兼容IOS6)

之前写过一篇文章在任意UIView上显示Badge,但IOS6上失败了,原来是苹果将Badge的类名改了,所以这里作下兼容,源码如下:

[plain] view plain copy print ?
  1. - (UIView *)showBadgeValue:(NSString *)strBadgeValue
  2. {
  3. UITabBar *tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
  4. UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"" image:nil tag:0];
  5. item.badgeValue = strBadgeValue;
  6. NSArray *array = [[NSArray alloc] initWithObjects:item, nil];
  7. tabBar.items = array;
  8. [item release];
  9. [array release];
  10. //寻找
  11. for (UIView *viewTab in tabBar.subviews) {
  12. for (UIView *subview in viewTab.subviews) {
  13. NSString *strClassName = [NSString stringWithUTF8String:object_getClassName(subview)];
  14. if ([strClassName isEqualToString:@"UITabBarButtonBadge"] ||
  15. [strClassName isEqualToString:@"_UIBadgeView"]) {
  16. //从原视图上移除
  17. [subview removeFromSuperview];
  18. //
  19. [self addSubview:subview];
  20. subview.frame = CGRectMake(self.frame.size.width-subview.frame.size.width, 0,
  21. subview.frame.size.width, subview.frame.size.height);
  22. [tabBar release];
  23. return subview;
  24. }
  25. }
  26. }
  27. [tabBar release];
  28. return nil;
  29. }
  30. - (void)removeBadgeValue
  31. {
  32. //
  33. for (UIView *subview in self.subviews) {
  34. NSString *strClassName = [NSString stringWithUTF8String:object_getClassName(subview)];
  35. if ([strClassName isEqualToString:@"UITabBarButtonBadge"] ||
  36. [strClassName isEqualToString:@"_UIBadgeView"]) {
  37. [subview removeFromSuperview];
  38. break;
  39. }
  40. }
  41. }

一个方法是显示Badge用的,一个是隐藏(移除)用的。

你可能感兴趣的:(在任意UIView上显示Badge(兼容IOS6))