// // ZZBadgeButton.m // zzjk // // Created by 沙狐 on 2020/6/15. // Copyright © 2020 沙狐. All rights reserved. // #import "ZZBadgeButton.h" @interface ZZBadgeButton () @property(nonatomic,weak) UIImageView *badgeImageView; @property(nonatomic,weak) UILabel *badgeLabel; @end @implementation ZZBadgeButton - (instancetype)init{ self = [super init]; if (self) { [self setupSubView]; } return self; } - (void)setupSubView{ UIImageView *badgeImageView = [[UIImageView alloc] init]; self.badgeImageView = badgeImageView; [self addSubview:badgeImageView]; UILabel *badgeLabel = [[UILabel alloc] init]; badgeLabel.font = FontADA_(11); badgeLabel.textAlignment = NSTextAlignmentCenter; badgeLabel.textColor = KKWhiteColorColor; badgeLabel.layer.cornerRadius = Adapted(7); badgeLabel.layer.masksToBounds = YES; self.badgeLabel = badgeLabel; [badgeImageView addSubview:badgeLabel]; } - (void)setBadge:(NSInteger)badge { if (badge > 0) { NSString *string = (badge > 99) ? @"99+" : [NSString stringWithFormat:@"%zd", badge]; self.badgeImageView.hidden = NO; self.badgeLabel.text = string; self.badgeLabel.backgroundColor = UIColor.redColor; CGFloat width = [string heightForFont:self.badgeLabel.font width:CGFLOAT_MAX]; if (string.length > 1) { self.badgeImageView.image = [self resizedImageWithName:@"my_order_big_border"]; self.badgeImageView.size = CGSizeMake(width + Adapted(10), Adapted(14)); } else { self.badgeImageView.image = [UIImage imageNamed:@"my_order_small_border"]; self.badgeImageView.size = CGSizeMake(Adapted(14), Adapted(14)); } self.badgeLabel.size = self.badgeImageView.size; } else { self.badgeImageView.hidden = YES; self.badgeLabel.backgroundColor = UIColor.clearColor; } } - (void)layoutSubviews { [super layoutSubviews]; self.imageView.top = 0; self.imageView.centerX = self.width / 2; [self.titleLabel sizeToFit]; self.titleLabel.top = self.imageView.bottom + 5; self.titleLabel.centerX = self.imageView.centerX; self.height = self.titleLabel.bottom; self.badgeImageView.centerY = self.imageView.top + Adapted(3); self.badgeImageView.centerX = self.imageView.right; } - (UIImage *)resizedImageWithName:(NSString *)name { return [self resizedImageWithName:name left:0.5 top:0.5]; } - (UIImage *)resizedImageWithName:(NSString *)name left:(CGFloat)left top:(CGFloat)top { UIImage *image = [UIImage imageNamed:name]; return [image stretchableImageWithLeftCapWidth:image.size.width * left topCapHeight:image.size.height * top]; } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code } */ @end