iOS中TabBarItem设置红点的示例分析
更新:HHH   时间:2023-1-8


这篇文章将为大家详细讲解有关iOS中TabBarItem设置红点的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

实现原理:

其实是自定义一个view,将view添加到UITabBar上面,也可以是一个按钮,设置背景图片,和label。

废话少说直接上代码

搞一个UITabBar的分类

#import <UIKit/UIKit.h>
@interface UITabBar (Extension)
- (void)showBadgeOnItmIndex:(int)index;
- (void)hideBadgeOnItemIndex:(int)index;
@end
#import "UITabBar+Extension.h"
#define TabbarItemNums 5.0
@implementation UITabBar (badge)
//显示红点
- (void)showBadgeOnItmIndex:(int)index{
 [self removeBadgeOnItemIndex:index];
 //新建小红点
 UIView *bview = [[UIView alloc]init];
 bview.tag = 888+index;
 bview.layer.cornerRadius = 5;
 bview.clipsToBounds = YES;
 bview.backgroundColor = [UIColor redColor];
 CGRect tabFram = self.frame;

 float percentX = (index+0.6)/TabbarItemNums;
 CGFloat x = ceilf(percentX*tabFram.size.width);
 CGFloat y = ceilf(0.1*tabFram.size.height);
 bview.frame = CGRectMake(x, y, 10, 10);
 [self addSubview:bview];
 [self bringSubviewToFront:bview];
}
//隐藏红点
-(void)hideBadgeOnItemIndex:(int)index{
 [self removeBadgeOnItemIndex:index];
}
//移除控件
- (void)removeBadgeOnItemIndex:(int)index{
 for (UIView*subView in self.subviews) {
  if (subView.tag == 888+index) {
   [subView removeFromSuperview];
  }
 }
}
@end

最后在子控制器调用就可以啦

[self.tabBarController.tabBar showBadgeOnItmIndex:4];

关于“iOS中TabBarItem设置红点的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

返回移动开发教程...