2019-04-07给TabBar添加未读消息小红点儿

第一步,建一个UITabBar的category类别

image.png

第二步:上代码

#import <UIKit/UIKit.h>

@interface UITabBar (badge)

- (void)showBadgeOnItemIndex:(int)index;   //显示小红点

- (void)hideBadgeOnItemIndex:(int)index; //隐藏小红点

@end

#import "UITabBar+badge.h"
#define TabbarItemNums 4.0    //tabbar的数量

@implementation UITabBar (badge)
- (void)showBadgeOnItemIndex:(int)index{  

    //移除之前的小红点
    [self removeBadgeOnItemIndex:index];

    //新建小红点
    UIView *badgeView = [[UIView alloc]init];
    badgeView.tag = 888 + index;
    badgeView.layer.cornerRadius = 5;
    badgeView.backgroundColor = [UIColor redColor];
    CGRect tabFrame = self.frame;

    //确定小红点的位置
    float percentX = (index +0.6) / TabbarItemNums;
    CGFloat x = ceilf(percentX * tabFrame.size.width);
    CGFloat y = ceilf(0.1 * tabFrame.size.height);
    badgeView.frame = CGRectMake(x, y, 10, 10);
    [self addSubview:badgeView];

}

- (void)hideBadgeOnItemIndex:(int)index{

    //移除小红点
    [self removeBadgeOnItemIndex:index];

}

- (void)removeBadgeOnItemIndex:(int)index{

    //按照tag值进行移除
    for (UIView *subView in self.subviews) {

        if (subView.tag == 888+index) {

            [subView removeFromSuperview];

        }
    }
}

@end

第三步,在需要用到的地方使用

//显示
[self.tabBarController.tabBar showBadgeOnItemIndex:2];

//隐藏
[self.tabBarController.tabBar hideBadgeOnItemIndex:2]
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 真正的成长,是深入扎根城市最基本层,体验不一样的收获!偶尔学会苦中作乐,生活也别是一番滋味!身体健康,稳定工作...
    龙的心_48aa阅读 906评论 0 0
  • The things that fascinate us about cats are as follows: t...
    化真阅读 1,261评论 0 1
  • 有的时候就是这样,总是在寻找,寻找一个让自己满意的答案,满意的说法,满意的理由,满意的你自己。 世界是怎样的,你是...
    彼得德鲁克阅读 903评论 0 0
  • 总是这样,越是缺少什么越爱炫耀什么。是你也是我。
    Amo_阿默阅读 1,638评论 0 0
  • 就在刚刚,胃又开始痛,绞痛,痛到走路直不起腰,每走一步就觉得胃被撕裂。 那个瞬间,我还是不争气的想起了你。 想起几...
    七尾青阅读 4,249评论 4 0