自定义tabBarItem的角标颜色、大小

最近项目需要用到角标,但样式跟系统默认的不一样,于是决定自己写一个分类来实现,大小和颜色可根据自己需求调整。

  • 第一步:新建文件选择New File
  • 第二步:选择Objective-c File然后填写文件名,选择File TypeCategory,Class为UITabBar,点击Next
  • 第三步:.h文件里添加显示隐藏的方法,例如:
@interface UITabBar (YZbadge)
- (void)showBadgeOnItemIndex:(int)index WithCount:(NSInteger)count;   //显示
- (void)hideBadgeOnItemIndex:(int)index; //隐藏
@end
  • 第四步:.m文件里实现显示隐藏的方法,例如:
//显示
- (void)showBadgeOnItemIndex:(int)index WithCount:(NSInteger)count{
    //移除之前的圆点
    [self removeBadgeOnItemIndex:index];
    
    //新建圆点
    UILabel *badgeView = [[UILabel alloc]init];
    badgeView.textColor = [UIColor whiteColor];
    badgeView.text = [NSString stringWithFormat:@"%ld",count];
    badgeView.font = [UIFont systemFontOfSize:10];
    badgeView.textAlignment = NSTextAlignmentCenter;
    badgeView.tag = 10000 + index;
    badgeView.layer.cornerRadius = 7.5;//圆形
    badgeView.clipsToBounds = YES;
    badgeView.backgroundColor = ;//颜色
    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-3);
    badgeView.frame = CGRectMake(x, y, 15, 15);//圆形大小为10
    [self addSubview:badgeView];
}  
//隐藏
- (void)hideBadgeOnItemIndex:(int)index{
    //移除
    [self removeBadgeOnItemIndex:index];
}
//移除圆点
- (void)removeBadgeOnItemIndex:(int)index{
    for (UIView *subView in self.subviews) {
        if (subView.tag == 10000+index) {
            [subView removeFromSuperview];
        }
    }
}

  • 代码写完之后可以运行测试了,在需要的地方用下面的代码调用一下
[self.tabBarController.tabBar showBadgeOnItemIndex:3 WithCount:badgeCount];
[self.tabBarController.tabBar hideBadgeOnItemIndex:3];

想用懒加载的童鞋可以自己改一下,改完控制badgeView.hidden就可以了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,132评论 25 708
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,218评论 2 33
  • 很想談談崔健的《一塊紅布》。 喜歡上一首歌總是忍不住的單曲循環,開始單曲循環《一塊紅布》是被劉明輝的翻唱感...
    别人家的小孩阅读 336评论 0 1
  • ssh:“SSH keys are a way to identify trusted computers wit...
    nuannuan_nuan阅读 958评论 0 0
  • 1.感恩早餐的白水,润肺润嗓,谢谢谢谢谢谢 2.感恩双脚可以行走,带我去上班,谢谢谢谢谢谢 3.感恩买早餐的阿姨,...
    桃七阅读 185评论 0 0