AttributedLabel.m 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. //
  2. // AttributedLabel.m
  3. // WildFireChat
  4. //
  5. // Created by heavyrain.lee on 2018/5/15.
  6. // Copyright © 2018 WildFireChat. All rights reserved.
  7. //
  8. #import "AttributedLabel.h"
  9. #import <CoreText/CoreText.h>
  10. @interface AttributedLabel()
  11. @property(nonatomic, strong)NSMutableArray *stringArray;
  12. @property(nonatomic, strong)NSMutableArray *rangeArray;
  13. @end
  14. @implementation AttributedLabel
  15. - (void)setText:(NSString *)text {
  16. self.attributedText = [self subStr:text];
  17. self.userInteractionEnabled = YES;
  18. }
  19. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  20. UITouch *touch = [touches anyObject];
  21. CFIndex index = [self characterIndexAtPoint:[touch locationInView:self]];
  22. for(NSValue *value in self.rangeArray) {
  23. NSRange range=[value rangeValue];
  24. if (range.location <= index && (range.location+range.length) >= index) {
  25. NSInteger i=[self.rangeArray indexOfObject:value];
  26. NSString *str = self.stringArray[i];
  27. NSLog(@"touch url %@", str);
  28. NSString *pattern =@"[0-9]{5,12}";
  29. NSPredicate*pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
  30. BOOL isNumber = [pred evaluateWithObject:str];
  31. if (isNumber) {
  32. if ([self.attributedLabelDelegate respondsToSelector:@selector(didSelectPhoneNumber:)]) {
  33. [self.attributedLabelDelegate didSelectPhoneNumber:str];
  34. }
  35. } else {
  36. if ([self.attributedLabelDelegate respondsToSelector:@selector(didSelectUrl:)]) {
  37. [self.attributedLabelDelegate didSelectUrl:str];
  38. }
  39. }
  40. }
  41. }
  42. [super touchesBegan:touches withEvent:event];
  43. }
  44. -(NSMutableAttributedString*)subStr:(NSString *)string {
  45. NSError *error;
  46. //可以识别url的正则表达式
  47. NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
  48. NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
  49. options:NSRegularExpressionCaseInsensitive
  50. error:&error];
  51. NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
  52. NSMutableArray *arr=[[NSMutableArray alloc]init];
  53. NSMutableArray *rangeArr=[[NSMutableArray alloc]init];
  54. self.stringArray = arr;
  55. self.rangeArray = rangeArr;
  56. for (NSTextCheckingResult *match in arrayOfAllMatches) {
  57. NSString* substringForMatch;
  58. substringForMatch = [string substringWithRange:match.range];
  59. [arr addObject:substringForMatch];
  60. }
  61. NSString *subStr=string;
  62. for (NSString *str in arr) {
  63. [rangeArr addObject:[self rangesOfString:str inString:subStr]];
  64. }
  65. NSString *pattern =@"[0-9]{5,11}";
  66. regex = [NSRegularExpression regularExpressionWithPattern:pattern
  67. options:NSRegularExpressionCaseInsensitive
  68. error:&error];
  69. arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
  70. for (NSTextCheckingResult *match in arrayOfAllMatches) {
  71. NSString* substringForMatch;
  72. substringForMatch = [string substringWithRange:match.range];
  73. [arr addObject:substringForMatch];
  74. }
  75. subStr=string;
  76. for (NSString *str in arr) {
  77. [rangeArr addObject:[self rangesOfString:str inString:subStr]];
  78. }
  79. NSMutableAttributedString *attributedText;
  80. attributedText=[[NSMutableAttributedString alloc]initWithString:subStr attributes:@{NSFontAttributeName :self.font}];
  81. for(NSValue *value in rangeArr) {
  82. NSInteger index=[rangeArr indexOfObject:value];
  83. NSRange range=[value rangeValue];
  84. [attributedText addAttribute:NSLinkAttributeName value:[NSURL URLWithString:[arr objectAtIndex:index]] range:range];
  85. [attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
  86. }
  87. return attributedText;
  88. }
  89. //获取查找字符串在母串中的NSRange
  90. - (NSValue *)rangesOfString:(NSString *)searchString inString:(NSString *)str {
  91. NSRange searchRange = NSMakeRange(0, [str length]);
  92. NSRange range;
  93. if ((range = [str rangeOfString:searchString options:0 range:searchRange]).location != NSNotFound) {
  94. searchRange = NSMakeRange(NSMaxRange(range), [str length] - NSMaxRange(range));
  95. }
  96. return [NSValue valueWithRange:range];
  97. }
  98. - (CFIndex)characterIndexAtPoint:(CGPoint)point {
  99. ////////
  100. NSMutableAttributedString* optimizedAttributedText = [self.attributedText mutableCopy];
  101. [self.attributedText enumerateAttribute:(NSString*)kCTParagraphStyleAttributeName inRange:NSMakeRange(0, [optimizedAttributedText length]) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
  102. if (value == nil) {
  103. return ;
  104. }
  105. NSMutableParagraphStyle* paragraphStyle = [value mutableCopy];
  106. if ([paragraphStyle lineBreakMode] == kCTLineBreakByTruncatingTail) {
  107. [paragraphStyle setLineBreakMode:kCTLineBreakByWordWrapping];
  108. }
  109. [optimizedAttributedText removeAttribute:(NSString*)kCTParagraphStyleAttributeName range:range];
  110. [optimizedAttributedText addAttribute:(NSString*)kCTParagraphStyleAttributeName value:paragraphStyle range:range];
  111. }];
  112. ////////
  113. if (!CGRectContainsPoint(self.bounds, point)) {
  114. return NSNotFound;
  115. }
  116. CGRect textRect = [self textRect];
  117. if (!CGRectContainsPoint(textRect, point)) {
  118. return NSNotFound;
  119. }
  120. // Offset tap coordinates by textRect origin to make them relative to the origin of frame
  121. point = CGPointMake(point.x - textRect.origin.x, point.y - textRect.origin.y);
  122. // Convert tap coordinates (start at top left) to CT coordinates (start at bottom left)
  123. point = CGPointMake(point.x, textRect.size.height - point.y);
  124. //////
  125. CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)optimizedAttributedText);
  126. CGMutablePathRef path = CGPathCreateMutable();
  127. CGPathAddRect(path, NULL, textRect);
  128. CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, [self.attributedText length]), path, NULL);
  129. if (frame == NULL) {
  130. CFRelease(path);
  131. return NSNotFound;
  132. }
  133. CFArrayRef lines = CTFrameGetLines(frame);
  134. NSInteger numberOfLines = self.numberOfLines > 0 ? MIN(self.numberOfLines, CFArrayGetCount(lines)) : CFArrayGetCount(lines);
  135. //NSLog(@"num lines: %d", numberOfLines);
  136. if (numberOfLines == 0) {
  137. CFRelease(frame);
  138. CFRelease(path);
  139. return NSNotFound;
  140. }
  141. NSUInteger idx = NSNotFound;
  142. CGPoint lineOrigins[numberOfLines];
  143. CTFrameGetLineOrigins(frame, CFRangeMake(0, numberOfLines), lineOrigins);
  144. for (CFIndex lineIndex = 0; lineIndex < numberOfLines; lineIndex++) {
  145. CGPoint lineOrigin = lineOrigins[lineIndex];
  146. CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex);
  147. // Get bounding information of line
  148. CGFloat ascent, descent, leading, width;
  149. width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
  150. CGFloat yMin = floor(lineOrigin.y - descent);
  151. CGFloat yMax = ceil(lineOrigin.y + ascent);
  152. // Check if we've already passed the line
  153. if (point.y > yMax) {
  154. break;
  155. }
  156. // Check if the point is within this line vertically
  157. if (point.y >= yMin) {
  158. // Check if the point is within this line horizontally
  159. if (point.x >= lineOrigin.x && point.x <= lineOrigin.x + width) {
  160. // Convert CT coordinates to line-relative coordinates
  161. CGPoint relativePoint = CGPointMake(point.x - lineOrigin.x, point.y - lineOrigin.y);
  162. idx = CTLineGetStringIndexForPosition(line, relativePoint);
  163. break;
  164. }
  165. }
  166. }
  167. CFRelease(frame);
  168. CFRelease(path);
  169. return idx;
  170. }
  171. - (CGRect)textRect {
  172. CGRect textRect = [self textRectForBounds:self.bounds limitedToNumberOfLines:self.numberOfLines];
  173. textRect.origin.y = (self.bounds.size.height - textRect.size.height)/2;
  174. if (self.textAlignment == NSTextAlignmentCenter) {
  175. textRect.origin.x = (self.bounds.size.width - textRect.size.width)/2;
  176. }
  177. if (self.textAlignment == NSTextAlignmentRight) {
  178. textRect.origin.x = self.bounds.size.width - textRect.size.width;
  179. }
  180. return textRect;
  181. }
  182. @end