在任意UIView上显示Badge

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以调整徽章的位置。


转载于:https://my.oschina.net/u/2242007/blog/352918

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值