新UI马甲包

BABadgeLabel.m 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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, 18, 18)];
  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. }
  43. #pragma mark - 根据文字内容、高度和字体返回 宽度
  44. CG_INLINE CGFloat
  45. BAKit_LabelWidthWithTextAndFont(NSString *text, CGFloat height, UIFont *font){
  46. CGSize size = CGSizeMake(MAXFLOAT, height);
  47. NSDictionary *attributesDic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
  48. CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDic context:nil];
  49. return frame.size.width;
  50. }
  51. @end