//
//  UITabBar+Extension.m
//  YJJ
//
//  Created by Luo yuntao on 2018/11/16.
//  Copyright © 2018年 YJJ. All rights reserved.
//

#import "UITabBar+Extension.h"
@implementation UITabBar (Extension)

// 显示小红点
- (void)showBadgeOnTabIndex:(NSInteger)index number:(NSInteger)number{
    
    NSInteger tabCount = self.items.count;
    
    // 移除之前的小红点
    [self removeBadgeOnItemIndex:index];
    
    // 新建小红点
    UILabel *badgeView = [[UILabel alloc]init];
    badgeView.tag = 888 + index;
    badgeView.layer.cornerRadius = 5.0;// 圆形
    badgeView.backgroundColor = [UIColor redColor];// 颜色：红色
    CGRect tabFrame = self.frame;
    
    CGFloat spae=0;
    // 确定小红点的位置
      CGFloat percentX = (index + 0.6) / tabCount; // 0.7控制小红点位置，值越大小红点越靠右
      CGFloat x = ceilf(percentX * tabFrame.size.width);
      CGFloat y = ceilf(5);
    if (IS_IPAD) {
        spae=(tabFrame.size.width-tabCount*30)/(tabCount+1);
          percentX = -10;
          x = (spae+30)*(index+1)+percentX;
          y = 5;
    }

    badgeView.clipsToBounds = YES;
    [self addSubview:badgeView];
    
    badgeView.textColor=[UIColor whiteColor];
    badgeView.font=[UIFont systemFontOfSize:10];
    badgeView.textAlignment=NSTextAlignmentCenter;
    badgeView.layer.cornerRadius = 5.0;// 圆形
    badgeView.frame = CGRectMake(x, y, 10.0, 10.0);// 圆形大小为10
//    badgeView.text=[NSString stringWithFormat:@"%ld",number];
    if(number==0){
        badgeView.hidden=YES;
    }else{
        badgeView.hidden=NO;
//        if (number>99) {
//            badgeView.text=@"99+";
//            badgeView.frame = CGRectMake(x, y, 22.0, 16.0);// 圆形大小为10
//        }
    }
    
}

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

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


#pragma mark --- 显示图片
-(void)showBadgeOnTabbarItemIndex:(NSInteger)index withImageName:(NSString *)imageName withHideOrShow:(BOOL)isShow{
    
    NSInteger tabCount = self.items.count;
    // 移除之前的小红点
    [self removeBadgeOnItemIndex:index];
    if (!isShow) {
    // 新建小红点
    UIImageView *badgeView = [[UIImageView alloc]init];
    badgeView.tag = 999 + index;
    CGRect tabFrame = self.frame;
    
    CGFloat spae=0;
    // 确定小红点的位置
      CGFloat percentX = (index + 0.6) / tabCount; // 0.7控制小红点位置，值越大小红点越靠右
      CGFloat x = ceilf(percentX * tabFrame.size.width);
      CGFloat y = ceilf(-5);
    if (IS_IPAD) {
        spae=(tabFrame.size.width-tabCount*30)/(tabCount+1);
          percentX = -10;
          x = (spae+30)*(index+1)+percentX;
          y = -8;
    }
    badgeView.image = [UIImage imageNamed:imageName];
        badgeView.frame = CGRectMake(x, y,  20, 20.0);
    [self addSubview:badgeView];
    }
}
@end
