AttributedLabel.m 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. }
  29. }
  30. [super touchesBegan:touches withEvent:event];
  31. }
  32. -(NSMutableAttributedString*)subStr:(NSString *)string {
  33. NSError *error;
  34. //可以识别url的正则表达式
  35. 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\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
  36. NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
  37. options:NSRegularExpressionCaseInsensitive
  38. error:&error];
  39. NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
  40. NSMutableArray *arr=[[NSMutableArray alloc]init];
  41. NSMutableArray *rangeArr=[[NSMutableArray alloc]init];
  42. self.stringArray = arr;
  43. self.rangeArray = rangeArr;
  44. for (NSTextCheckingResult *match in arrayOfAllMatches) {
  45. NSString* substringForMatch;
  46. substringForMatch = [string substringWithRange:match.range];
  47. [arr addObject:substringForMatch];
  48. }
  49. NSString *subStr=string;
  50. for (NSString *str in arr) {
  51. [rangeArr addObject:[self rangesOfString:str inString:subStr]];
  52. }
  53. NSMutableAttributedString *attributedText;
  54. attributedText=[[NSMutableAttributedString alloc]initWithString:subStr attributes:@{NSFontAttributeName :self.font}];
  55. for(NSValue *value in rangeArr) {
  56. NSInteger index=[rangeArr indexOfObject:value];
  57. NSRange range=[value rangeValue];
  58. [attributedText addAttribute:NSLinkAttributeName value:[NSURL URLWithString:[arr objectAtIndex:index]] range:range];
  59. [attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
  60. }
  61. return attributedText;
  62. }
  63. //获取查找字符串在母串中的NSRange
  64. - (NSValue *)rangesOfString:(NSString *)searchString inString:(NSString *)str {
  65. NSRange searchRange = NSMakeRange(0, [str length]);
  66. NSRange range;
  67. if ((range = [str rangeOfString:searchString options:0 range:searchRange]).location != NSNotFound) {
  68. searchRange = NSMakeRange(NSMaxRange(range), [str length] - NSMaxRange(range));
  69. }
  70. return [NSValue valueWithRange:range];
  71. }
  72. - (CFIndex)characterIndexAtPoint:(CGPoint)point {
  73. ////////
  74. NSMutableAttributedString* optimizedAttributedText = [self.attributedText mutableCopy];
  75. [self.attributedText enumerateAttribute:(NSString*)kCTParagraphStyleAttributeName inRange:NSMakeRange(0, [optimizedAttributedText length]) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
  76. if (value == nil) {
  77. return ;
  78. }
  79. NSMutableParagraphStyle* paragraphStyle = [value mutableCopy];
  80. if ([paragraphStyle lineBreakMode] == kCTLineBreakByTruncatingTail) {
  81. [paragraphStyle setLineBreakMode:kCTLineBreakByWordWrapping];
  82. }
  83. [optimizedAttributedText removeAttribute:(NSString*)kCTParagraphStyleAttributeName range:range];
  84. [optimizedAttributedText addAttribute:(NSString*)kCTParagraphStyleAttributeName value:paragraphStyle range:range];
  85. }];
  86. ////////
  87. if (!CGRectContainsPoint(self.bounds, point)) {
  88. return NSNotFound;
  89. }
  90. CGRect textRect = [self textRect];
  91. if (!CGRectContainsPoint(textRect, point)) {
  92. return NSNotFound;
  93. }
  94. // Offset tap coordinates by textRect origin to make them relative to the origin of frame
  95. point = CGPointMake(point.x - textRect.origin.x, point.y - textRect.origin.y);
  96. // Convert tap coordinates (start at top left) to CT coordinates (start at bottom left)
  97. point = CGPointMake(point.x, textRect.size.height - point.y);
  98. //////
  99. CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)optimizedAttributedText);
  100. CGMutablePathRef path = CGPathCreateMutable();
  101. CGPathAddRect(path, NULL, textRect);
  102. CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, [self.attributedText length]), path, NULL);
  103. if (frame == NULL) {
  104. CFRelease(path);
  105. return NSNotFound;
  106. }
  107. CFArrayRef lines = CTFrameGetLines(frame);
  108. NSInteger numberOfLines = self.numberOfLines > 0 ? MIN(self.numberOfLines, CFArrayGetCount(lines)) : CFArrayGetCount(lines);
  109. //NSLog(@"num lines: %d", numberOfLines);
  110. if (numberOfLines == 0) {
  111. CFRelease(frame);
  112. CFRelease(path);
  113. return NSNotFound;
  114. }
  115. NSUInteger idx = NSNotFound;
  116. CGPoint lineOrigins[numberOfLines];
  117. CTFrameGetLineOrigins(frame, CFRangeMake(0, numberOfLines), lineOrigins);
  118. for (CFIndex lineIndex = 0; lineIndex < numberOfLines; lineIndex++) {
  119. CGPoint lineOrigin = lineOrigins[lineIndex];
  120. CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex);
  121. // Get bounding information of line
  122. CGFloat ascent, descent, leading, width;
  123. width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
  124. CGFloat yMin = floor(lineOrigin.y - descent);
  125. CGFloat yMax = ceil(lineOrigin.y + ascent);
  126. // Check if we've already passed the line
  127. if (point.y > yMax) {
  128. break;
  129. }
  130. // Check if the point is within this line vertically
  131. if (point.y >= yMin) {
  132. // Check if the point is within this line horizontally
  133. if (point.x >= lineOrigin.x && point.x <= lineOrigin.x + width) {
  134. // Convert CT coordinates to line-relative coordinates
  135. CGPoint relativePoint = CGPointMake(point.x - lineOrigin.x, point.y - lineOrigin.y);
  136. idx = CTLineGetStringIndexForPosition(line, relativePoint);
  137. break;
  138. }
  139. }
  140. }
  141. CFRelease(frame);
  142. CFRelease(path);
  143. return idx;
  144. }
  145. - (CGRect)textRect {
  146. CGRect textRect = [self textRectForBounds:self.bounds limitedToNumberOfLines:self.numberOfLines];
  147. textRect.origin.y = (self.bounds.size.height - textRect.size.height)/2;
  148. if (self.textAlignment == NSTextAlignmentCenter) {
  149. textRect.origin.x = (self.bounds.size.width - textRect.size.width)/2;
  150. }
  151. if (self.textAlignment == NSTextAlignmentRight) {
  152. textRect.origin.x = self.bounds.size.width - textRect.size.width;
  153. }
  154. return textRect;
  155. }
  156. @end