iOS TabBarItem Set Red Dot (Unread Message)

  • 2021-12-11 09:12:02
  • OfStack

Implementation principle:

It is actually a custom view, add view to UITabBar, or a button, set the background picture, and label.

Cut the crap and go straight to the code

Make a classification of 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)
// Show red dots 
- (void)showBadgeOnItmIndex:(int)index{
 [self removeBadgeOnItemIndex:index];
 // New Little Red Dot 
 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];
}
// Hide red dots 
-(void)hideBadgeOnItemIndex:(int)index{
 [self removeBadgeOnItemIndex:index];
}
// To remove a control 
- (void)removeBadgeOnItemIndex:(int)index{
 for (UIView*subView in self.subviews) {
  if (subView.tag == 888+index) {
   [subView removeFromSuperview];
  }
 }
}
@end

Finally, it can be called in the sub-controller

[self.tabBarController.tabBar showBadgeOnItmIndex:4];


Related articles: