在任意UIView上显示Badge

来源:互联网 发布:淘宝刷收藏有什么用 编辑:程序博客网 时间:2024/05/17 01:07

UITabBar的选项卡上有时会需要显示一个红圈,红圈里是数字或者其他字符,术语叫徽章,比如微信主页面主选项卡上会用这种方式提示新消息条数,但也想在其他地方显示这个徽章怎么办呢?比如微信中每个联系人的头像右上角显示该联系人的新消息条数。当然有第三方的源码,但效果还是不如系统提供的好。

系统这个徽章的类叫UITabBarButtonBadge,但是该类是个私有类,开发人员不能用。先贴源码

[plain] view plaincopy
  1. + (UIView *)addBadgeViewTo:(UIView *)superview withBadgeValue:(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 compare:@"UITabBarButtonBadge"] == NSOrderedSame) {  
  15.                 //从原视图上移除  
  16.                 [subview removeFromSuperview];  
  17.                 //  
  18.                 [superview addSubview:subview];  
  19.                 [tabBar release];  
  20.                 return subview;  
  21.             }  
  22.         }  
  23.     }  
  24.     [tabBar release];  
  25.     return nil;  
  26. }  

输入参数为想要显示徽章的UIView和徽章上要显示的字符串,返回徽章的UIView以调整徽章的位置。
0 0