為UITabBar添加分類(lèi)方法
.h
#import <UIKit/UIKit.h>
@interface UITabBar (SJCRedDotBar)
- (void)showBadgeOnItemIndex:(NSInteger)index; ///<顯示小紅點(diǎn)
- (void)hideBadgeOnItemIndex:(NSInteger)index; ///<隱藏小紅點(diǎn)
- (void)showBadge:(NSString *)badge onIndex:(NSInteger)index;
- (void)hideBadgeOnIndex:(NSInteger)index;
@end
.m
#import "UITabBar+SJCRedDotBar.h"
#define TabbarItemNums 5
@implementation UITabBar (SJCRedDotBar)
//顯示小紅點(diǎn)
- (void)showBadgeOnItemIndex:(NSInteger)index{
//移除之前的小紅點(diǎn)
[self removeBadgeOnItemIndex:index];
//新建小紅點(diǎn)
UIView *badgeView = [[UIView alloc]init];
badgeView.tag = 888 + index;
badgeView.layer.cornerRadius = 4.0;//圓形
badgeView.backgroundColor = ThemeRedColor;//[UIColor redColor];//顏色:紅色
CGRect tabFrame = self.frame;
//確定小紅點(diǎn)的位置
CGFloat 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, 8.0, 8.0);//圓形大小為10
badgeView.clipsToBounds = YES;
[self addSubview:badgeView];
}
//隱藏小紅點(diǎn)
- (void)hideBadgeOnItemIndex:(NSInteger)index{
//移除小紅點(diǎn)
[self removeBadgeOnItemIndex:index];
}
//移除小紅點(diǎn)
- (void)removeBadgeOnItemIndex:(NSInteger)index{
//按照tag值進(jìn)行移除
for (UIView *subView in self.subviews) {
if (subView.tag == 888+index) {
[subView removeFromSuperview];
}
}
}
- (void)showBadge:(NSString *)badge onIndex:(NSInteger)index{
[self remoBadgeAtIndex:index];
if ([badge integerValue]>999) badge = @"999+";
UILabel *badgeLab = [UILabel new];
badgeLab.tag = 999+index;
badgeLab.layer.cornerRadius = 10;
badgeLab.layer.masksToBounds = YES;
badgeLab.layer.borderWidth = 2;
badgeLab.layer.borderColor = WhiteColor.CGColor;
badgeLab.font = SFDisplayMedium(9);
badgeLab.textColor = WhiteColor;
badgeLab.backgroundColor = ThemeRedColor;
badgeLab.textAlignment = NSTextAlignmentCenter;
badgeLab.text = badge;
CGRect tabFrame = self.frame;
CGFloat percentX = (index + 0.6) / TabbarItemNums;
CGFloat x = ceilf(percentX * tabFrame.size.width);
CGFloat y = ceilf(0.05 * tabFrame.size.height);
CGFloat w = [badge widthForFont:SFDisplayMedium(9)];
badgeLab.frame = CGRectMake(x, y, MIN((self.frame.size.width/TabbarItemNums-22), MAX(20, w+10)), 20);
badgeLab.clipsToBounds = YES;
[self addSubview:badgeLab];
}
- (void)hideBadgeOnIndex:(NSInteger)index{
[self remoBadgeAtIndex:index];
}
- (void)remoBadgeAtIndex:(NSInteger)index{
for (UIView *subView in self.subviews) {
if (subView.tag == 999+index) {
[subView removeFromSuperview];
}
}
}
@end