酷店

BABadgeLabel.m 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // BABadgeLabel.m
  3. // BAKit
  4. //
  5. // Created by boai on 2017/7/29.
  6. // Copyright © 2017年 boai. All rights reserved.
  7. //
  8. #import "BABadgeLabel.h"
  9. @implementation BABadgeLabel
  10. + (instancetype)ba_badgeLabelDefaultBadgeLabel
  11. {
  12. // 默认为系统 tabBarItem 的 badge 大小
  13. return [[BABadgeLabel alloc] initWithFrame:CGRectMake(0, 0, 12, 12)];
  14. }
  15. - (instancetype)initWithFrame:(CGRect)frame
  16. {
  17. if (self = [super initWithFrame:frame]) {
  18. [self setupUI];
  19. }
  20. return self;
  21. }
  22. - (void)setupUI
  23. {
  24. self.textColor = [UIColor whiteColor];
  25. self.font = [UIFont systemFontOfSize:10];
  26. self.textAlignment = NSTextAlignmentCenter;
  27. self.layer.cornerRadius = self.height * 0.5;
  28. self.layer.masksToBounds = YES;
  29. self.backgroundColor = [UIColor colorWithRed:1.00 green:0.17 blue:0.15 alpha:1.00];
  30. }
  31. - (void)setText:(NSString *)text
  32. {
  33. [super setText:text];
  34. // 根据内容调整label的宽度
  35. // CGFloat stringWidth = BAKit_LabelWidthWithTextAndFont(text, self.height, self.font);
  36. // if (self.height > stringWidth + self.height * 10 / 18)
  37. // {
  38. // self.width = self.height;
  39. // return;
  40. // }
  41. // self.width = self.height * 5 / 18 + stringWidth + self.height * 5 / 18;
  42. // self.width = 2 + stringWidth ;
  43. // self.height = self.width;
  44. // [self sizeToFit];
  45. self.adjustsFontSizeToFitWidth = YES;
  46. self.height = self.width;
  47. self.layer.cornerRadius = self.height * 0.5;
  48. }
  49. #pragma mark - 根据文字内容、高度和字体返回 宽度
  50. CG_INLINE CGFloat
  51. BAKit_LabelWidthWithTextAndFont(NSString *text, CGFloat height, UIFont *font){
  52. CGSize size = CGSizeMake(MAXFLOAT, height);
  53. NSDictionary *attributesDic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
  54. CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDic context:nil];
  55. return frame.size.width;
  56. }
  57. @end