iOS 自定义设置UITabBar 角标 badgeView 的背景色

版权声明:本文为博主原创文章,转载请注明。 https://blog.csdn.net/a44496913/article/details/60315909

UITabBar 角标 badgeView 的默认背景色是红色,有时候也需要根据需求进行修改,但在网上大致寻找了一下,发现有两种主要的处理的方式:

1.完全自定义UITabBar;

2.不使用官方的badgeView,而是对UITabbar进行扩展,自定义一个view或者label,并将其放在UITabBar上;

   这里就不上代码了,想了解的可以看这篇文章 : http://www.jianshu.com/p/ccc0d24408fd


3.除了以上两种方式外,还有另外一种方式 ------ 直接对官方的控件进行修改,这种方式也需要对 UITabBar 进行扩展,过程如下:

#import "UITabBar+Custom.h"

@implementation UITabBar (Custom)

/**
 *  该方法的调用一定要在设置了tabBarItem.badgeValue 之后使用
 */
- (void)badgeViews:(void (^)(UIView *badgeView, UILabel *badgeLabel, UIView *badgeBackground))block {
    
    if (block) {
        
        for (UIView *tabBarButton in self.subviews)
        {
            /** 设置badgeView背景色就可设置角标的背景色 */
            for (UIView *badgeView in tabBarButton.subviews)
            {
                NSString *className = NSStringFromClass([badgeView class]);
                
                if ([className rangeOfString:@"BadgeView"].location != NSNotFound)
                {
                    /** badgeLabel 就是角标上数字显示框 */
                    UILabel *badgeLabel;
                    
                    /** badgeBackground 在badgeView上可能不存在,如果存在就可以进行自定义修改 */
                    UIView *badgeBackground;
                    
                    for (UIView *badgeSubview in badgeView.subviews)
                    {
                        NSString *className = NSStringFromClass([badgeSubview class]);
                        
                        if ([badgeSubview isKindOfClass:[UILabel class]])
                        {
                            badgeLabel = (UILabel *)badgeSubview;
                            
                        } else if ([className rangeOfString:@"BadgeBackground"].location != NSNotFound) {
                            
                            badgeBackground = badgeSubview;
                        }
                    }
                    
                    block(badgeView, badgeLabel, badgeBackground);
                }
            }
        }
    }
}

@end

调用该方法场景是这样的

[self.tabBar badgeViews:^(UIView *badgeView, UILabel *badgeLabel, UIView *badgeBackground) {
    
    
    //这里进行相关自定义设置,如:背景色、显示内容,添加背景图片...
    
    badgeView.backgroundColor = [UIColor redColor];
    
}];


扫描二维码关注公众号,回复: 3186475 查看本文章


猜你喜欢

转载自blog.csdn.net/a44496913/article/details/60315909