第二篇、Swift_自定义 tabbar 的 badgeValue显示样式

在实际的开发中,我们常常需要根据实际的需求,去改变bageValue的显示样式,默认是红色的背景,白色的字体颜色

使用方式:

class BKTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.addCustomTabbar()
        
        
        
    }

    func addCustomTabbar()  {
        
        let newTabbar                       = BKTabbar(frame: self.tabBar.frame)
        newTabbar.items                     = self.tabBar.items
        newTabbar.badgeValueTextColor       = UIColor.black
        newTabbar.badgeValueBackgroundColor = UIColor.yellow
        self.setValue(newTabbar, forKey: "tabBar")
        
        
        
    }
  
    
}

 

设置数值的方式:

self.tabBarItem.badgeValue = "100"

通过 UIViewControler 的 tabBarItem.badgeValue 属性设置 badgeValue的值 , 跟系统的 badgeValue 设置方式一致,只是屏蔽了系统的实现方法,改成自定义 badgeValue 的显示样式

 

 

0.UITabBarItem+Extension

#import <UIKit/UIKit.h>

@interface UITabBarItem (Extension)

/**
 *  tabBarItem 的 tag
 */
@property (nonatomic,assign) NSInteger index;

/**
 *   自定义 tabBar 的 badgeValue
 */
@property (nonatomic,copy,nullable) NSString *customBadgeValue;

@end

 

#import "UITabBarItem+Extension.h"
#import <objc/runtime.h>

static NSString *const kItemTagKey     = @"tags";

static NSString *const kItemBadgeValue = @"badgeValue";


@implementation UITabBarItem (Extension)

- (void)setIndex:(NSInteger)index {
    
    NSNumber *number =  [NSNumber numberWithInteger:index];
    objc_setAssociatedObject(self, &kItemTagKey, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
}


- (NSInteger)index {
    
    NSNumber *number = (NSNumber *)objc_getAssociatedObject(self, &kItemTagKey);
    return number.integerValue;
    
}

- (void)setCustomBadgeValue:(NSString *)customBadgeValue {
    
    objc_setAssociatedObject(self, &kItemBadgeValue, customBadgeValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TabbarBadgeValueChange" object:self];

}

- (NSString *)customBadgeValue {
    
    NSString *value = (NSString *)objc_getAssociatedObject(self, &kItemBadgeValue);

    return value;
}

- (void)setBadgeValue:(NSString *)badgeValue {
    
    self.customBadgeValue   = badgeValue;
}

@end

 

1.自定义的tabbar

#import <UIKit/UIKit.h>

/**
 *  自定义 tabBar 解决了 badgeValue 显示问题
 */
@interface BKTabbar : UITabBar

/**
 *  自定义 badgeValue 的背景色
 */
@property (nonatomic,strong,nullable) UIColor *badgeValueBackgroundColor;
/**
 *  自定义 badgeValue 的文字颜色
 */
@property (nonatomic,strong,nullable) UIColor *badgeValueTextColor;


@end

 

#import "BKTabbar.h"
#import "UITabBarItem+Extension.h"


@interface BKTabbar ()

@property (nonatomic,strong,nullable) NSMutableDictionary *badgeValuesDic;

@end

@implementation BKTabbar

- (NSMutableDictionary *)badgeValuesDic {
    if (!_badgeValuesDic) {
        _badgeValuesDic = [NSMutableDictionary dictionary];
    }
    return _badgeValuesDic;
}

- (void)layoutSubviews {
    
    [super layoutSubviews];
    
    NSInteger indexTag        = 1000;
    NSMutableArray *tempArray = [NSMutableArray array];
    
    // 便利 tabbar 所有子视图 
    for (UIView *sub in self.subviews) {
        
        if ([sub isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            
            if ([tempArray containsObject:sub]) continue;
            [tempArray addObject:sub];
            
        }
    }
    // 临时数组保存四个按钮
    [tempArray sortUsingComparator:^NSComparisonResult(UIButton *btn1, UIButton *btn2) {
        
        NSNumber *number1 = [NSNumber numberWithFloat:btn1.frame.origin.x];
        NSNumber *number2 = [NSNumber numberWithFloat:btn2.frame.origin.x];
        
        return [number1 compare :number2];
        
    }];

   // 便利数组给 badgeValue 赋值
    for (UIButton *button in tempArray) {
    
        NSString *key       = [NSString stringWithFormat:@"%@",@(indexTag)];
        CGFloat buttonWidth = button.frame.size.width;
        UILabel *oldLabel   = [button viewWithTag:key.integerValue];

        // 先找重用 不存在就创建一个
        if (!oldLabel) {
            
            UILabel *label            = [[UILabel alloc] init];
            label.tag                 = indexTag;
            label.textColor           = self.badgeValueTextColor;
            label.textAlignment       = NSTextAlignmentCenter;
            label.font                = [UIFont systemFontOfSize:13.0f];
            label.backgroundColor     = self.badgeValueBackgroundColor;
            label.layer.masksToBounds = YES;
            [button addSubview:label];
            oldLabel                  = label;

        }

        oldLabel.hidden             = YES;
        UITabBarItem *currentItem   = self.badgeValuesDic[key];
        indexTag++;

        if (!currentItem) continue;
        if (currentItem.customBadgeValue == nil) continue;
        if ([currentItem.customBadgeValue isEqualToString:@"0"]) return;
        oldLabel.hidden             = NO;

        NSString *title             = currentItem.customBadgeValue;

        CGFloat itemWidth           = 0.0f;
        CGFloat cornerRadius        = 0.0f;
        NSInteger textLength        = title.length > 5 ? 5 : title.length;
        itemWidth                   = 18.0f + (textLength-1) *8.0f;
        cornerRadius                = 9.0f;

        oldLabel.frame              = CGRectMake(buttonWidth *0.58f, 2.0f, itemWidth, 18.0f);
        oldLabel.text               = title;
        oldLabel.layer.cornerRadius = cornerRadius;

    }
    
 
    
}

- (void)setItems:(NSArray<UITabBarItem *> *)items {
    
    [super setItems:items];
    
    NSInteger index       = 1000;

    for (UITabBarItem *item in self.items ) {

        item.index = index;

        [self.badgeValuesDic setValue:item forKey:[NSString stringWithFormat:@"%ld",(long)item.index]];
        
        index ++;
    }
    
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(badgeValueDidChange:) name:@"TabbarBadgeValueChange" object:nil];
        self.badgeValueBackgroundColor = [UIColor redColor];
        self.badgeValueTextColor       = [UIColor redColor];

    }
    return self;
}

#pragma mark - tabbar的 badgeValue 发生改变的通知

- (void)badgeValueDidChange:(NSNotification *)noti {
    
    UITabBarItem *item       = (UITabBarItem *)noti.object;

    if (!item || item.index == 0) return;

    NSString *key            = [NSString stringWithFormat:@"%ld",(long)item.index];

    self.badgeValuesDic[key] = item;

    [self setNeedsLayout];

}

@end

 

posted on 2016-11-05 14:09  久冬不雨  阅读(1486)  评论(0编辑  收藏  举报