在任意UIView上显示Badge

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

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

+ (UIView *)addBadgeViewTo:(UIView *)superview withBadgeValue:(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 compare:@"UITabBarButtonBadge"] == NSOrderedSame) {
				//从原视图上移除
				[subview removeFromSuperview];
                //
                [superview addSubview:subview];
                [tabBar release];
                return subview;
			}
		}
	}
	[tabBar release];
    return nil;
}

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

原文地址:https://www.cnblogs.com/yjh4866/p/6253878.html