iOS开发小笔记 | 封装一个带角标的button

先看设计图:

现在要封装的就是中间那个带角标的按钮。

思路:

继承UIButton,在button的titleLabel右上角放一个label。

代码:


#pragma mark - 构造方法

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self customInitialize];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self customInitialize];
    }
    return self;
}

- (void)customInitialize {
    // button属性设置
    self.clipsToBounds = NO;
    [self.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    //------- 角标label -------//
    self.badgeLabel = [[UILabel alloc] init];
    [self.titleLabel addSubview:self.badgeLabel];
    self.badgeLabel.backgroundColor = [UIColor redColor];
    self.badgeLabel.font = [UIFont systemFontOfSize:10];
    self.badgeLabel.textColor = [UIColor whiteColor];
    self.badgeLabel.layer.cornerRadius = 6;
    self.badgeLabel.clipsToBounds = YES;
    // 默认隐藏
    self.badgeLabel.hidden = YES;
}

#pragma mark - 布局变化时调整UI

- (void)layoutSubviews {
    [super layoutSubviews];
    [self refresh];
}

- (void)refresh {
    [self layoutIfNeeded];
    // 调整角标label的大小和位置
    [self.badgeLabel sizeToFit];
    self.badgeLabel.frame = CGRectMake(CGRectGetWidth(self.titleLabel.frame)-5, -5, CGRectGetWidth(self.badgeLabel.frame), 12);
}

#pragma mark - 显示角标

/**
 显示角标
 
 @param badgeNumber 角标数量
 */
- (void)showBadgeWithNumber:(NSInteger)badgeNumber {
    self.badgeLabel.hidden = NO;
    // 注意数字前后各留一个空格,不然太紧凑
    self.badgeLabel.text = [NSString stringWithFormat:@" %ld ",badgeNumber];
    // 赋值后调整UI
    [self refresh];
}

#pragma mark - 隐藏角标

/** 隐藏角标 */
- (void)hideBadge {
    self.badgeLabel.hidden = YES;
}

封装的效果:

iOS开发小笔记 | 封装一个带角标的button_第1张图片
支持动态布局

上图的代码:

// 绝对布局
self.badgeButton1 = [[CQBadgeButton alloc] initWithFrame:CGRectMake(90, 100, 180, 30)];
[self.view addSubview:self.badgeButton1];
[self.badgeButton1 setTitle:@"呵呵哒" forState:UIControlStateNormal];
[self.badgeButton1 showBadgeWithNumber:3];

// 自动布局
self.badgeButton2 = [[CQBadgeButton alloc] init];
[self.badgeButton2 showBadgeWithNumber:999];
[self.view addSubview:self.badgeButton2];
[self.badgeButton2 setTitle:@"么么哒么么哒么么么么哒" forState:UIControlStateNormal];
[self.badgeButton2 mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.right.height.mas_equalTo(self.badgeButton1);
    make.top.mas_equalTo(self.badgeButton1.mas_bottom).mas_offset(30);
}];

// 拖的按钮
[self.badgeButton3 showBadgeWithNumber:888];

demo

https://github.com/CaiWanFeng/CQBadgeButton

你可能感兴趣的:(iOS开发小笔记 | 封装一个带角标的button)