UGLabel.m 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. //
  2. // UGLabel.m
  3. // VideoHeadline
  4. //
  5. // Created by admin on 2020/8/17.
  6. // Copyright © 2020 IgCoding. All rights reserved.
  7. //
  8. #import "UGLabel.h"
  9. @interface UGLabel ()
  10. @end
  11. @implementation UGLabel
  12. - (instancetype)initWithFrame:(CGRect)frame
  13. {
  14. if(self = [super initWithFrame:frame])
  15. {
  16. self.edgeInsets = UIEdgeInsetsMake(3, 7, 3, 7);
  17. }
  18. return self;
  19. }
  20. - (instancetype)initWithCoder:(NSCoder *)aDecoder
  21. {
  22. if (self = [super initWithCoder:aDecoder]) {
  23. self.edgeInsets = UIEdgeInsetsMake(3, 7, 3, 7);
  24. }
  25. return self;
  26. }
  27. - (void)awakeFromNib
  28. {
  29. [super awakeFromNib];
  30. self.edgeInsets = UIEdgeInsetsMake(3, 7, 3, 7);
  31. }
  32. + (UIEdgeInsets)edgeInsets
  33. {
  34. /*- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);
  35. 方法计算label的大小时,由于不会调用textRectForBounds方法,并不会计算自己通过edgeInsets插入的内边距,而是实际的大小,因此手动返回进行修正*/
  36. return UIEdgeInsetsMake(3, 7, 3, 7);
  37. }
  38. + (NSDictionary *)textLabelArrtibute
  39. {
  40. // 可以通过 NSMutableParagraphStyle修改左边内边距
  41. NSMutableDictionary *attribute = [NSMutableDictionary dictionary];
  42. attribute[NSFontAttributeName] = [UIFont systemFontOfSize:16];
  43. NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
  44. paragraphStyle.lineSpacing = 5;//行间距
  45. paragraphStyle.alignment = NSTextAlignmentJustified;
  46. attribute[NSParagraphStyleAttributeName] = paragraphStyle;
  47. return attribute;
  48. }
  49. #pragma mark 设置第一行和最后一行距离label的距离
  50. -(CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
  51. {
  52. //注意传入的UIEdgeInsetsInsetRect(bounds, self.edgeInsets),bounds是真正的绘图区域
  53. CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets) limitedToNumberOfLines:numberOfLines];
  54. rect.origin.x -= self.edgeInsets.left;
  55. rect.origin.y -= self.edgeInsets.top;
  56. rect.size.width += self.edgeInsets.left + self.edgeInsets.right;
  57. rect.size.height += self.edgeInsets.top + self.edgeInsets.bottom;
  58. return rect;
  59. }
  60. - (void)drawTextInRect:(CGRect)rect
  61. {
  62. [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
  63. }
  64. @end