UILabel+RightAndLeft.m 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //
  2. // UILabel+RightAndLeft.m
  3. // smartRhino
  4. //
  5. // Created by tederen on 2019/11/28.
  6. // Copyright © 2019 tederen. All rights reserved.
  7. //
  8. #import "UILabel+RightAndLeft.h"
  9. @implementation UILabel (RightAndLeft)
  10. - (void)textAlignmentLeftAndRight{
  11. [self textAlignmentLeftAndRightWith:CGRectGetWidth(self.frame)];
  12. }
  13. - (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth{
  14. if(self.text==nil||self.text.length==0) {
  15. return;
  16. }
  17. CGSize size = [self.text boundingRectWithSize:CGSizeMake(labelWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.font} context:nil].size;
  18. NSInteger length = (self.text.length-1);
  19. NSString* lastStr = [self.text substringWithRange:NSMakeRange(self.text.length-1,1)];
  20. if([lastStr isEqualToString:@":"]||[lastStr isEqualToString:@":"]) {
  21. length = (self.text.length-2);
  22. }
  23. CGFloat margin = (labelWidth - size.width)/length;
  24. NSNumber * number = [NSNumber numberWithFloat:margin];
  25. NSMutableAttributedString* attribute = [[NSMutableAttributedString alloc]initWithString:self.text];
  26. [attribute addAttribute:NSKernAttributeName value:number range:NSMakeRange(0,length)];
  27. self.attributedText= attribute;
  28. }
  29. @end