UILabel+TD.m 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // UILabel+TD.m
  3. // smartRhino
  4. //
  5. // Created by tederen on 2019/10/22.
  6. // Copyright © 2019 tederen. All rights reserved.
  7. //
  8. #import "UILabel+TD.h"
  9. @implementation UILabel (TD)
  10. - (void)highlightString:(NSString *)string color:(UIColor *)color {
  11. NSMutableAttributedString *att = [[NSMutableAttributedString alloc]initWithString:self.text];
  12. NSString *temp = nil;
  13. for(int i = 0; i < [self.text length] - [string length]; i++){
  14. temp = [self.text substringWithRange:NSMakeRange(i,[string length])];
  15. if ([temp isEqualToString:string]) {
  16. NSRange range = NSMakeRange(i,[string length]);
  17. [att addAttribute:NSForegroundColorAttributeName value:color range:range];
  18. }
  19. }
  20. self.attributedText = att;
  21. }
  22. - (NSAttributedString *)subhighlightString:(NSString *)string color:(UIColor *)color {
  23. NSMutableAttributedString *att = [[NSMutableAttributedString alloc]initWithString:self.text];
  24. NSString *temp = nil;
  25. for(int i = 0; i <= [self.text length] - [string length]; i++){
  26. temp = [self.text substringWithRange:NSMakeRange(i,[string length])];
  27. if ([temp isEqualToString:string]) {
  28. NSRange range = NSMakeRange(i,[string length]);
  29. [att addAttribute:NSForegroundColorAttributeName value:color range:range];
  30. }
  31. }
  32. return att;
  33. }
  34. - (void)highlightString:(NSString *)string color:(UIColor *)color withSpace:(CGFloat)space withFont:(UIFont*)font setLineSpace:(NSUInteger)headIndent setTextSpace:(CGFloat)textspace{
  35. if (string.length == 0) {
  36. return;
  37. }
  38. NSMutableAttributedString *att = [[NSMutableAttributedString alloc]initWithAttributedString:[self subhighlightString:string color:color]];
  39. NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
  40. paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
  41. paraStyle.alignment = NSTextAlignmentNatural;
  42. paraStyle.lineSpacing = space; //设置行间距
  43. paraStyle.hyphenationFactor = 1.0;
  44. paraStyle.firstLineHeadIndent = font.pointSize * headIndent;
  45. paraStyle.paragraphSpacingBefore = 0.0;
  46. paraStyle.headIndent = 0;
  47. NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@(textspace)
  48. };
  49. [att addAttributes:dic range:NSMakeRange(0,self.text.length)];
  50. self.attributedText = att;
  51. }
  52. @end