自定义tab上的badge和小红点

IMG_0220.PNG

为UITabBar添加分类方法

.h

#import 

@interface UITabBar (SJCRedDotBar)


- (void)showBadgeOnItemIndex:(NSInteger)index;   ///<显示小红点

- (void)hideBadgeOnItemIndex:(NSInteger)index;  ///<隐藏小红点

- (void)showBadge:(NSString *)badge onIndex:(NSInteger)index;

- (void)hideBadgeOnIndex:(NSInteger)index;

@end

.m

#import "UITabBar+SJCRedDotBar.h"


#define TabbarItemNums  5

@implementation UITabBar (SJCRedDotBar)


//显示小红点
- (void)showBadgeOnItemIndex:(NSInteger)index{
    //移除之前的小红点
    [self removeBadgeOnItemIndex:index];
    
    //新建小红点
    UIView *badgeView = [[UIView alloc]init];
    badgeView.tag = 888 + index;
    badgeView.layer.cornerRadius = 4.0;//圆形
    badgeView.backgroundColor = ThemeRedColor;//[UIColor redColor];//颜色:红色
    CGRect tabFrame = self.frame;
    
    //确定小红点的位置
    CGFloat percentX = (index + 0.6) / TabbarItemNums;
    CGFloat x = ceilf(percentX * tabFrame.size.width);
    CGFloat y = ceilf(0.1 * tabFrame.size.height);
    badgeView.frame = CGRectMake(x, y, 8.0, 8.0);//圆形大小为10
    badgeView.clipsToBounds = YES;
    [self addSubview:badgeView];
}

//隐藏小红点
- (void)hideBadgeOnItemIndex:(NSInteger)index{
    //移除小红点
    [self removeBadgeOnItemIndex:index];
}

//移除小红点
- (void)removeBadgeOnItemIndex:(NSInteger)index{
    //按照tag值进行移除
    for (UIView *subView in self.subviews) {
        if (subView.tag == 888+index) {
            [subView removeFromSuperview];
        }
    }
}

- (void)showBadge:(NSString *)badge onIndex:(NSInteger)index{
    [self remoBadgeAtIndex:index];
    
    if ([badge integerValue]>999) badge = @"999+";
    
    UILabel *badgeLab = [UILabel new];
    badgeLab.tag = 999+index;
    badgeLab.layer.cornerRadius = 10;
    badgeLab.layer.masksToBounds = YES;
    badgeLab.layer.borderWidth = 2;
    badgeLab.layer.borderColor = WhiteColor.CGColor;
    badgeLab.font = SFDisplayMedium(9);
    badgeLab.textColor = WhiteColor;
    badgeLab.backgroundColor = ThemeRedColor;
    badgeLab.textAlignment = NSTextAlignmentCenter;
    badgeLab.text = badge;
    
    CGRect tabFrame = self.frame;
    
    CGFloat percentX = (index + 0.6) / TabbarItemNums;
    CGFloat x = ceilf(percentX * tabFrame.size.width);
    CGFloat y = ceilf(0.05 * tabFrame.size.height);
    CGFloat w = [badge widthForFont:SFDisplayMedium(9)];
    badgeLab.frame = CGRectMake(x, y, MIN((self.frame.size.width/TabbarItemNums-22), MAX(20, w+10)), 20);
    badgeLab.clipsToBounds = YES;
    [self addSubview:badgeLab];
}

- (void)hideBadgeOnIndex:(NSInteger)index{
    [self remoBadgeAtIndex:index];
}

- (void)remoBadgeAtIndex:(NSInteger)index{
    for (UIView *subView in self.subviews) {
        if (subView.tag == 999+index) {
            [subView removeFromSuperview];
        }
    }
}
@end

你可能感兴趣的:(自定义tab上的badge和小红点)