为UITabBarItem自定义红点

由于UITabBarItem上系统自带的bage并不能满足项目的需求,所以需要自定义小红点,以来展示。下面为实现代码,简单方便。当然如果需要其他样式,自己完全可以根据以下方法进行改造。

//
//  UITabBar+YGDot.h
//  DailyYoga
//
//  Created by Beryter on 2017/1/24.
//  Copyright © 2017年 DailyYoga. All rights reserved.
//

#import 

@interface UITabBar (YGDot)
/*!
 * @brief   显示小红点
 * @param   index 将要显示小红点的tabbarItem的索引(第一个item的索引为0)
 * @return
 */
- (void)showDotAtIndex:(NSInteger)index;
/*!
 * @brief   隐藏小红点
 * @param   index 将要隐藏小红点的tabbarItem的索引(第一个item的索引为0)
 * @return
 */
- (void)hiddenDotAtIndex:(NSInteger)index;
@end
//
//  UITabBar+YGDot.m
//  DailyYoga
//
//  Created by Beryter on 2017/1/24.
//  Copyright © 2017年 DailyYoga. All rights reserved.
//

#import "UITabBar+YGDot.h"

@implementation UITabBar (YGDot)

- (void)showDotAtIndex:(NSInteger)index
{
    NSMutableArray *array = [NSMutableArray array];
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [array addObject:view];
        }
    }
    if (index >= array.count) {
        return;
    }
    UIView *tabBarButton = array[index];
    CGFloat selectedImageWidth = 0;
    CGFloat topMargin = 0;
    
    for (UIView *view in tabBarButton.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]) {
            selectedImageWidth = view.frame.size.width;
            topMargin = view.frame.origin.y;
        }
    }
    
    for (UIView *view in tabBarButton.subviews) {
        if (view.tag == 999) {
            [view removeFromSuperview];
        }
    }
    UIView *dot = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMidX(tabBarButton.bounds) + selectedImageWidth / 2 + 2.5, topMargin, 2.5 * 2, 2.5 * 2)];
    dot.backgroundColor = [UIColor redColor];
    dot.layer.cornerRadius = 2.5;
    dot.tag = 999;
    [tabBarButton addSubview:dot];
}

- (void)hiddenDotAtIndex:(NSInteger)index
{
    NSMutableArray *array = [NSMutableArray array];
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [array addObject:view];
        }
    }
    if (index >= array.count) {
        return;
    }
    UIView *tabBarButton = array[index];
    for (UIView *view in tabBarButton.subviews) {
        if (view.tag == 999) {
            [view removeFromSuperview];
        }
    }
}
@end

可加群一起交流共同学习:801216530。

你可能感兴趣的:(为UITabBarItem自定义红点)