TabbarButton.h
@interface TabbarButton : UIButton @property (nonatomic, strong) UIButton *badgeValueView; - (void)setItemBadgeNumber:(NSInteger)number; - (CGRect)imageRectForContentRect:(CGRect)contentRect; - (CGRect)titleRectForContentRect:(CGRect)contentRect; @end
TabbarButton.m
@implementation TabbarButton - (id)init { if (self = [super init]) { [self createBadgeValueView]; } return self; } #pragma mark - 创建BadgeValueView - (void)createBadgeValueView { CGFloat x = 39 - badgeValueViewWH + 5; CGFloat y = -5; _badgeValueView = [[UIButton alloc] initWithFrame:CGRectMake(x, y,badgeValueViewWH, badgeValueViewWH)]; [_badgeValueView setBackgroundImage:[UIImage imageNamed:@"badgeBG"] forState:UIControlStateNormal]; _badgeValueView.titleLabel.font = kFont12; [_badgeValueView setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; _badgeValueView.hidden = YES; _badgeValueView.adjustsImageWhenHighlighted = NO; [self addSubview:_badgeValueView]; } #pragma mark - 设置小红圈里的数字 - (void)setItemBadgeNumber:(NSInteger)number { if (number != 0) { if (self.badgeValueView.hidden) { self.badgeValueView.hidden = NO; } [self.badgeValueView setTitle:[NSString stringWithFormat:@"%d",number] forState:(UIControlStateNormal)]; }else{ self.badgeValueView.hidden = YES; } }
调用自定义按钮:
//1.创建自定义的按钮 TabbarButton *button = [[TabbarButton alloc]init]; button.tag = index; CGFloat btnX = kScreenW / 4 * (index - 10) + 15; button.frame = CGRectMake(btnX, 5, 45, 45); //2.设置按钮图片和事件 [button setImage:[UIImage imageNamed:normal] forState:UIControlStateNormal]; [button setImage:[UIImage imageNamed:selected] forState:UIControlStateDisabled]; [button addTarget:self action:@selector(changeViewController:) forControlEvents:UIControlEventTouchDown]; //3.让图片在按钮内居中 button.imageView.contentMode = UIViewContentModeCenter; //4.创建按钮下面的文本 UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(btnX, 30, 45, 20)]; label.tag = index + 10; label.text = title; label.font = kFont11; label.textColor = [UIColor grayColor]; label.textAlignment = NSTextAlignmentCenter;
//添加到自定义的tabbar [_myTabBar addSubview:label]; [_myTabBar addSubview:button];
//设置按钮的BadgeNumber
[button setItemBadgeNumber:1];