為UITabBarItem自定義紅點

由于UITabBarItem上系統自帶的bage并不能滿足項目的需求,所以需要自定義小紅點,以來展示。下面為實現代碼,簡單方便。當然如果需要其他樣式,自己完全可以根據以下方法進行改造。

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

#import <UIKit/UIKit.h>

@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。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容