TTTAttributedLabel.m 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838
  1. // TTTAttributedLabel.m
  2. //
  3. // Copyright (c) 2011 Mattt Thompson (http://mattt.me)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. #import "TTTAttributedLabel.h"
  23. #import <QuartzCore/QuartzCore.h>
  24. #import <Availability.h>
  25. #import <objc/runtime.h>
  26. #define kTTTLineBreakWordWrapTextWidthScalingFactor (M_PI / M_E)
  27. static CGFloat const TTTFLOAT_MAX = 100000;
  28. NSString * const kTTTStrikeOutAttributeName = @"TTTStrikeOutAttribute";
  29. NSString * const kTTTBackgroundFillColorAttributeName = @"TTTBackgroundFillColor";
  30. NSString * const kTTTBackgroundFillPaddingAttributeName = @"TTTBackgroundFillPadding";
  31. NSString * const kTTTBackgroundStrokeColorAttributeName = @"TTTBackgroundStrokeColor";
  32. NSString * const kTTTBackgroundLineWidthAttributeName = @"TTTBackgroundLineWidth";
  33. NSString * const kTTTBackgroundCornerRadiusAttributeName = @"TTTBackgroundCornerRadius";
  34. const NSTextAlignment TTTTextAlignmentLeft = NSTextAlignmentLeft;
  35. const NSTextAlignment TTTTextAlignmentCenter = NSTextAlignmentCenter;
  36. const NSTextAlignment TTTTextAlignmentRight = NSTextAlignmentRight;
  37. const NSTextAlignment TTTTextAlignmentJustified = NSTextAlignmentJustified;
  38. const NSTextAlignment TTTTextAlignmentNatural = NSTextAlignmentNatural;
  39. const NSLineBreakMode TTTLineBreakByWordWrapping = NSLineBreakByWordWrapping;
  40. const NSLineBreakMode TTTLineBreakByCharWrapping = NSLineBreakByCharWrapping;
  41. const NSLineBreakMode TTTLineBreakByClipping = NSLineBreakByClipping;
  42. const NSLineBreakMode TTTLineBreakByTruncatingHead = NSLineBreakByTruncatingHead;
  43. const NSLineBreakMode TTTLineBreakByTruncatingMiddle = NSLineBreakByTruncatingMiddle;
  44. const NSLineBreakMode TTTLineBreakByTruncatingTail = NSLineBreakByTruncatingTail;
  45. typedef NSTextAlignment TTTTextAlignment;
  46. typedef NSLineBreakMode TTTLineBreakMode;
  47. static inline CGFLOAT_TYPE CGFloat_ceil(CGFLOAT_TYPE cgfloat) {
  48. #if CGFLOAT_IS_DOUBLE
  49. return ceil(cgfloat);
  50. #else
  51. return ceilf(cgfloat);
  52. #endif
  53. }
  54. static inline CGFLOAT_TYPE CGFloat_floor(CGFLOAT_TYPE cgfloat) {
  55. #if CGFLOAT_IS_DOUBLE
  56. return floor(cgfloat);
  57. #else
  58. return floorf(cgfloat);
  59. #endif
  60. }
  61. static inline CGFLOAT_TYPE CGFloat_round(CGFLOAT_TYPE cgfloat) {
  62. #if CGFLOAT_IS_DOUBLE
  63. return round(cgfloat);
  64. #else
  65. return roundf(cgfloat);
  66. #endif
  67. }
  68. static inline CGFLOAT_TYPE CGFloat_sqrt(CGFLOAT_TYPE cgfloat) {
  69. #if CGFLOAT_IS_DOUBLE
  70. return sqrt(cgfloat);
  71. #else
  72. return sqrtf(cgfloat);
  73. #endif
  74. }
  75. static inline CGFloat TTTFlushFactorForTextAlignment(NSTextAlignment textAlignment) {
  76. switch (textAlignment) {
  77. case TTTTextAlignmentCenter:
  78. return 0.5f;
  79. case TTTTextAlignmentRight:
  80. return 1.0f;
  81. case TTTTextAlignmentLeft:
  82. default:
  83. return 0.0f;
  84. }
  85. }
  86. static inline NSDictionary * NSAttributedStringAttributesFromLabel(TTTAttributedLabel *label) {
  87. NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionary];
  88. [mutableAttributes setObject:label.font forKey:(NSString *)kCTFontAttributeName];
  89. [mutableAttributes setObject:label.textColor forKey:(NSString *)kCTForegroundColorAttributeName];
  90. [mutableAttributes setObject:@(label.kern) forKey:(NSString *)kCTKernAttributeName];
  91. NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
  92. paragraphStyle.alignment = label.textAlignment;
  93. paragraphStyle.lineSpacing = label.lineSpacing;
  94. paragraphStyle.minimumLineHeight = label.minimumLineHeight > 0 ? label.minimumLineHeight : label.font.lineHeight * label.lineHeightMultiple;
  95. paragraphStyle.maximumLineHeight = label.maximumLineHeight > 0 ? label.maximumLineHeight : label.font.lineHeight * label.lineHeightMultiple;
  96. paragraphStyle.lineHeightMultiple = label.lineHeightMultiple;
  97. paragraphStyle.firstLineHeadIndent = label.firstLineIndent;
  98. if (label.numberOfLines == 1) {
  99. paragraphStyle.lineBreakMode = label.lineBreakMode;
  100. } else {
  101. paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
  102. }
  103. [mutableAttributes setObject:paragraphStyle forKey:(NSString *)kCTParagraphStyleAttributeName];
  104. return [NSDictionary dictionaryWithDictionary:mutableAttributes];
  105. }
  106. static inline CGColorRef CGColorRefFromColor(id color);
  107. static inline NSDictionary * convertNSAttributedStringAttributesToCTAttributes(NSDictionary *attributes);
  108. static inline NSAttributedString * NSAttributedStringByScalingFontSize(NSAttributedString *attributedString, CGFloat scale) {
  109. NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy];
  110. [mutableAttributedString enumerateAttribute:(NSString *)kCTFontAttributeName inRange:NSMakeRange(0, [mutableAttributedString length]) options:0 usingBlock:^(id value, NSRange range, BOOL * __unused stop) {
  111. UIFont *font = (UIFont *)value;
  112. if (font) {
  113. NSString *fontName;
  114. CGFloat pointSize;
  115. if ([font isKindOfClass:[UIFont class]]) {
  116. fontName = font.fontName;
  117. pointSize = font.pointSize;
  118. } else {
  119. fontName = (NSString *)CFBridgingRelease(CTFontCopyName((__bridge CTFontRef)font, kCTFontPostScriptNameKey));
  120. pointSize = CTFontGetSize((__bridge CTFontRef)font);
  121. }
  122. [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName range:range];
  123. CTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef)fontName, CGFloat_floor(pointSize * scale), NULL);
  124. [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)fontRef range:range];
  125. CFRelease(fontRef);
  126. }
  127. }];
  128. return mutableAttributedString;
  129. }
  130. static inline NSAttributedString * NSAttributedStringBySettingColorFromContext(NSAttributedString *attributedString, UIColor *color) {
  131. if (!color) {
  132. return attributedString;
  133. }
  134. NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy];
  135. [mutableAttributedString enumerateAttribute:(NSString *)kCTForegroundColorFromContextAttributeName inRange:NSMakeRange(0, [mutableAttributedString length]) options:0 usingBlock:^(id value, NSRange range, __unused BOOL *stop) {
  136. BOOL usesColorFromContext = (BOOL)value;
  137. if (usesColorFromContext) {
  138. [mutableAttributedString setAttributes:[NSDictionary dictionaryWithObject:color forKey:(NSString *)kCTForegroundColorAttributeName] range:range];
  139. [mutableAttributedString removeAttribute:(NSString *)kCTForegroundColorFromContextAttributeName range:range];
  140. }
  141. }];
  142. return mutableAttributedString;
  143. }
  144. static inline CGSize CTFramesetterSuggestFrameSizeForAttributedStringWithConstraints(CTFramesetterRef framesetter, NSAttributedString *attributedString, CGSize size, NSUInteger numberOfLines) {
  145. CFRange rangeToSize = CFRangeMake(0, (CFIndex)[attributedString length]);
  146. CGSize constraints = CGSizeMake(size.width, TTTFLOAT_MAX);
  147. if (numberOfLines == 1) {
  148. // If there is one line, the size that fits is the full width of the line
  149. constraints = CGSizeMake(TTTFLOAT_MAX, TTTFLOAT_MAX);
  150. } else if (numberOfLines > 0) {
  151. // If the line count of the label more than 1, limit the range to size to the number of lines that have been set
  152. CGMutablePathRef path = CGPathCreateMutable();
  153. CGPathAddRect(path, NULL, CGRectMake(0.0f, 0.0f, constraints.width, TTTFLOAT_MAX));
  154. CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
  155. CFArrayRef lines = CTFrameGetLines(frame);
  156. if (CFArrayGetCount(lines) > 0) {
  157. NSInteger lastVisibleLineIndex = MIN((CFIndex)numberOfLines, CFArrayGetCount(lines)) - 1;
  158. CTLineRef lastVisibleLine = CFArrayGetValueAtIndex(lines, lastVisibleLineIndex);
  159. CFRange rangeToLayout = CTLineGetStringRange(lastVisibleLine);
  160. rangeToSize = CFRangeMake(0, rangeToLayout.location + rangeToLayout.length);
  161. }
  162. CFRelease(frame);
  163. CGPathRelease(path);
  164. }
  165. CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, rangeToSize, NULL, constraints, NULL);
  166. return CGSizeMake(CGFloat_ceil(suggestedSize.width), CGFloat_ceil(suggestedSize.height));
  167. }
  168. @interface TTTAccessibilityElement : UIAccessibilityElement
  169. @property (nonatomic, weak) UIView *superview;
  170. @property (nonatomic, assign) CGRect boundingRect;
  171. @end
  172. @implementation TTTAccessibilityElement
  173. - (CGRect)accessibilityFrame {
  174. return UIAccessibilityConvertFrameToScreenCoordinates(self.boundingRect, self.superview);
  175. }
  176. @end
  177. @interface TTTAttributedLabel ()
  178. @property (readwrite, nonatomic, copy) NSAttributedString *inactiveAttributedText;
  179. @property (readwrite, nonatomic, copy) NSAttributedString *renderedAttributedText;
  180. @property (readwrite, atomic, strong) NSDataDetector *dataDetector;
  181. @property (readwrite, nonatomic, strong) NSArray *linkModels;
  182. @property (readwrite, nonatomic, strong) TTTAttributedLabelLink *activeLink;
  183. @property (readwrite, nonatomic, strong) NSArray *accessibilityElements;
  184. - (void) longPressGestureDidFire:(UILongPressGestureRecognizer *)sender;
  185. @end
  186. @implementation TTTAttributedLabel {
  187. @private
  188. BOOL _needsFramesetter;
  189. CTFramesetterRef _framesetter;
  190. CTFramesetterRef _highlightFramesetter;
  191. }
  192. @dynamic text;
  193. @synthesize attributedText = _attributedText;
  194. #ifndef kCFCoreFoundationVersionNumber_iOS_7_0
  195. #define kCFCoreFoundationVersionNumber_iOS_7_0 847.2
  196. #endif
  197. + (void)load {
  198. static dispatch_once_t onceToken;
  199. dispatch_once(&onceToken, ^{
  200. if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iOS_7_0) {
  201. Class class = [self class];
  202. Class superclass = class_getSuperclass(class);
  203. NSArray *strings = @[
  204. NSStringFromSelector(@selector(isAccessibilityElement)),
  205. NSStringFromSelector(@selector(accessibilityElementCount)),
  206. NSStringFromSelector(@selector(accessibilityElementAtIndex:)),
  207. NSStringFromSelector(@selector(indexOfAccessibilityElement:)),
  208. ];
  209. for (NSString *string in strings) {
  210. SEL selector = NSSelectorFromString(string);
  211. IMP superImplementation = class_getMethodImplementation(superclass, selector);
  212. Method method = class_getInstanceMethod(class, selector);
  213. const char *types = method_getTypeEncoding(method);
  214. class_replaceMethod(class, selector, superImplementation, types);
  215. }
  216. }
  217. });
  218. }
  219. - (instancetype)initWithFrame:(CGRect)frame {
  220. self = [super initWithFrame:frame];
  221. if (!self) {
  222. return nil;
  223. }
  224. [self commonInit];
  225. return self;
  226. }
  227. - (void)commonInit {
  228. self.userInteractionEnabled = YES;
  229. #if !TARGET_OS_TV
  230. self.multipleTouchEnabled = NO;
  231. #endif
  232. self.textInsets = UIEdgeInsetsZero;
  233. self.lineHeightMultiple = 1.0f;
  234. self.linkModels = [NSArray array];
  235. self.linkBackgroundEdgeInset = UIEdgeInsetsMake(0.0f, -1.0f, 0.0f, -1.0f);
  236. NSMutableDictionary *mutableLinkAttributes = [NSMutableDictionary dictionary];
  237. [mutableLinkAttributes setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCTUnderlineStyleAttributeName];
  238. NSMutableDictionary *mutableActiveLinkAttributes = [NSMutableDictionary dictionary];
  239. [mutableActiveLinkAttributes setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCTUnderlineStyleAttributeName];
  240. NSMutableDictionary *mutableInactiveLinkAttributes = [NSMutableDictionary dictionary];
  241. [mutableInactiveLinkAttributes setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCTUnderlineStyleAttributeName];
  242. if ([NSMutableParagraphStyle class]) {
  243. [mutableLinkAttributes setObject:[UIColor blueColor] forKey:(NSString *)kCTForegroundColorAttributeName];
  244. [mutableActiveLinkAttributes setObject:[UIColor redColor] forKey:(NSString *)kCTForegroundColorAttributeName];
  245. [mutableInactiveLinkAttributes setObject:[UIColor grayColor] forKey:(NSString *)kCTForegroundColorAttributeName];
  246. } else {
  247. [mutableLinkAttributes setObject:(__bridge id)[[UIColor blueColor] CGColor] forKey:(NSString *)kCTForegroundColorAttributeName];
  248. [mutableActiveLinkAttributes setObject:(__bridge id)[[UIColor redColor] CGColor] forKey:(NSString *)kCTForegroundColorAttributeName];
  249. [mutableInactiveLinkAttributes setObject:(__bridge id)[[UIColor grayColor] CGColor] forKey:(NSString *)kCTForegroundColorAttributeName];
  250. }
  251. self.linkAttributes = [NSDictionary dictionaryWithDictionary:mutableLinkAttributes];
  252. self.activeLinkAttributes = [NSDictionary dictionaryWithDictionary:mutableActiveLinkAttributes];
  253. self.inactiveLinkAttributes = [NSDictionary dictionaryWithDictionary:mutableInactiveLinkAttributes];
  254. _extendsLinkTouchArea = NO;
  255. _longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self
  256. action:@selector(longPressGestureDidFire:)];
  257. self.longPressGestureRecognizer.delegate = self;
  258. [self addGestureRecognizer:self.longPressGestureRecognizer];
  259. }
  260. - (void)dealloc {
  261. if (_framesetter) {
  262. CFRelease(_framesetter);
  263. }
  264. if (_highlightFramesetter) {
  265. CFRelease(_highlightFramesetter);
  266. }
  267. if (_longPressGestureRecognizer) {
  268. [self removeGestureRecognizer:_longPressGestureRecognizer];
  269. }
  270. }
  271. #pragma mark -
  272. + (CGSize)sizeThatFitsAttributedString:(NSAttributedString *)attributedString
  273. withConstraints:(CGSize)size
  274. limitedToNumberOfLines:(NSUInteger)numberOfLines
  275. {
  276. if (!attributedString || attributedString.length == 0) {
  277. return CGSizeZero;
  278. }
  279. CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attributedString);
  280. CGSize calculatedSize = CTFramesetterSuggestFrameSizeForAttributedStringWithConstraints(framesetter, attributedString, size, numberOfLines);
  281. CFRelease(framesetter);
  282. return calculatedSize;
  283. }
  284. #pragma mark -
  285. - (void)setAttributedText:(NSAttributedString *)text {
  286. if ([text isEqualToAttributedString:_attributedText]) {
  287. return;
  288. }
  289. _attributedText = [text copy];
  290. [self setNeedsFramesetter];
  291. [self setNeedsDisplay];
  292. if ([self respondsToSelector:@selector(invalidateIntrinsicContentSize)]) {
  293. [self invalidateIntrinsicContentSize];
  294. }
  295. [super setText:[self.attributedText string]];
  296. }
  297. - (NSAttributedString *)renderedAttributedText {
  298. if (!_renderedAttributedText) {
  299. NSMutableAttributedString *fullString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
  300. if (self.attributedTruncationToken) {
  301. [fullString appendAttributedString:self.attributedTruncationToken];
  302. }
  303. NSAttributedString *string = [[NSAttributedString alloc] initWithAttributedString:fullString];
  304. self.renderedAttributedText = NSAttributedStringBySettingColorFromContext(string, self.textColor);
  305. }
  306. return _renderedAttributedText;
  307. }
  308. - (NSArray *) links {
  309. return [_linkModels valueForKey:@"result"];
  310. }
  311. - (void)setLinkModels:(NSArray *)linkModels {
  312. _linkModels = linkModels;
  313. self.accessibilityElements = nil;
  314. }
  315. - (void)setNeedsFramesetter {
  316. // Reset the rendered attributed text so it has a chance to regenerate
  317. self.renderedAttributedText = nil;
  318. _needsFramesetter = YES;
  319. }
  320. - (CTFramesetterRef)framesetter {
  321. if (_needsFramesetter) {
  322. @synchronized(self) {
  323. CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)self.renderedAttributedText);
  324. [self setFramesetter:framesetter];
  325. [self setHighlightFramesetter:nil];
  326. _needsFramesetter = NO;
  327. if (framesetter) {
  328. CFRelease(framesetter);
  329. }
  330. }
  331. }
  332. return _framesetter;
  333. }
  334. - (void)setFramesetter:(CTFramesetterRef)framesetter {
  335. if (framesetter) {
  336. CFRetain(framesetter);
  337. }
  338. if (_framesetter) {
  339. CFRelease(_framesetter);
  340. }
  341. _framesetter = framesetter;
  342. }
  343. - (CTFramesetterRef)highlightFramesetter {
  344. return _highlightFramesetter;
  345. }
  346. - (void)setHighlightFramesetter:(CTFramesetterRef)highlightFramesetter {
  347. if (highlightFramesetter) {
  348. CFRetain(highlightFramesetter);
  349. }
  350. if (_highlightFramesetter) {
  351. CFRelease(_highlightFramesetter);
  352. }
  353. _highlightFramesetter = highlightFramesetter;
  354. }
  355. #pragma mark -
  356. - (void)setEnabledTextCheckingTypes:(NSTextCheckingTypes)enabledTextCheckingTypes {
  357. if (self.enabledTextCheckingTypes == enabledTextCheckingTypes) {
  358. return;
  359. }
  360. _enabledTextCheckingTypes = enabledTextCheckingTypes;
  361. // one detector instance per type (combination), fast reuse e.g. in cells
  362. static NSMutableDictionary *dataDetectorsByType = nil;
  363. if (!dataDetectorsByType) {
  364. dataDetectorsByType = [NSMutableDictionary dictionary];
  365. }
  366. if (enabledTextCheckingTypes) {
  367. if (![dataDetectorsByType objectForKey:@(enabledTextCheckingTypes)]) {
  368. NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:enabledTextCheckingTypes
  369. error:nil];
  370. if (detector) {
  371. [dataDetectorsByType setObject:detector forKey:@(enabledTextCheckingTypes)];
  372. }
  373. }
  374. self.dataDetector = [dataDetectorsByType objectForKey:@(enabledTextCheckingTypes)];
  375. } else {
  376. self.dataDetector = nil;
  377. }
  378. }
  379. - (void)addLink:(TTTAttributedLabelLink *)link {
  380. [self addLinks:@[link]];
  381. }
  382. - (void)addLinks:(NSArray *)links {
  383. NSMutableArray *mutableLinkModels = [NSMutableArray arrayWithArray:self.linkModels];
  384. NSMutableAttributedString *mutableAttributedString = [self.attributedText mutableCopy];
  385. for (TTTAttributedLabelLink *link in links) {
  386. if (link.attributes) {
  387. [mutableAttributedString addAttributes:link.attributes range:link.result.range];
  388. }
  389. }
  390. self.attributedText = mutableAttributedString;
  391. [self setNeedsDisplay];
  392. [mutableLinkModels addObjectsFromArray:links];
  393. self.linkModels = [NSArray arrayWithArray:mutableLinkModels];
  394. }
  395. - (TTTAttributedLabelLink *)addLinkWithTextCheckingResult:(NSTextCheckingResult *)result
  396. attributes:(NSDictionary *)attributes
  397. {
  398. return [self addLinksWithTextCheckingResults:@[result] attributes:attributes].firstObject;
  399. }
  400. - (NSArray *)addLinksWithTextCheckingResults:(NSArray *)results
  401. attributes:(NSDictionary *)attributes
  402. {
  403. NSMutableArray *links = [NSMutableArray array];
  404. for (NSTextCheckingResult *result in results) {
  405. NSDictionary *activeAttributes = attributes ? self.activeLinkAttributes : nil;
  406. NSDictionary *inactiveAttributes = attributes ? self.inactiveLinkAttributes : nil;
  407. TTTAttributedLabelLink *link = [[TTTAttributedLabelLink alloc] initWithAttributes:attributes
  408. activeAttributes:activeAttributes
  409. inactiveAttributes:inactiveAttributes
  410. textCheckingResult:result];
  411. [links addObject:link];
  412. }
  413. [self addLinks:links];
  414. return links;
  415. }
  416. - (TTTAttributedLabelLink *)addLinkWithTextCheckingResult:(NSTextCheckingResult *)result {
  417. return [self addLinkWithTextCheckingResult:result attributes:self.linkAttributes];
  418. }
  419. - (TTTAttributedLabelLink *)addLinkToURL:(NSURL *)url
  420. withRange:(NSRange)range
  421. {
  422. return [self addLinkWithTextCheckingResult:[NSTextCheckingResult linkCheckingResultWithRange:range URL:url]];
  423. }
  424. - (TTTAttributedLabelLink *)addLinkToAddress:(NSDictionary *)addressComponents
  425. withRange:(NSRange)range
  426. {
  427. return [self addLinkWithTextCheckingResult:[NSTextCheckingResult addressCheckingResultWithRange:range components:addressComponents]];
  428. }
  429. - (TTTAttributedLabelLink *)addLinkToPhoneNumber:(NSString *)phoneNumber
  430. withRange:(NSRange)range
  431. {
  432. return [self addLinkWithTextCheckingResult:[NSTextCheckingResult phoneNumberCheckingResultWithRange:range phoneNumber:phoneNumber]];
  433. }
  434. - (TTTAttributedLabelLink *)addLinkToDate:(NSDate *)date
  435. withRange:(NSRange)range
  436. {
  437. return [self addLinkWithTextCheckingResult:[NSTextCheckingResult dateCheckingResultWithRange:range date:date]];
  438. }
  439. - (TTTAttributedLabelLink *)addLinkToDate:(NSDate *)date
  440. timeZone:(NSTimeZone *)timeZone
  441. duration:(NSTimeInterval)duration
  442. withRange:(NSRange)range
  443. {
  444. return [self addLinkWithTextCheckingResult:[NSTextCheckingResult dateCheckingResultWithRange:range date:date timeZone:timeZone duration:duration]];
  445. }
  446. - (TTTAttributedLabelLink *)addLinkToTransitInformation:(NSDictionary *)components
  447. withRange:(NSRange)range
  448. {
  449. return [self addLinkWithTextCheckingResult:[NSTextCheckingResult transitInformationCheckingResultWithRange:range components:components]];
  450. }
  451. #pragma mark -
  452. - (BOOL)containslinkAtPoint:(CGPoint)point {
  453. return [self linkAtPoint:point] != nil;
  454. }
  455. - (TTTAttributedLabelLink *)linkAtPoint:(CGPoint)point {
  456. // Stop quickly if none of the points to be tested are in the bounds.
  457. if (!CGRectContainsPoint(CGRectInset(self.bounds, -15.f, -15.f), point) || self.links.count == 0) {
  458. return nil;
  459. }
  460. TTTAttributedLabelLink *result = [self linkAtCharacterIndex:[self characterIndexAtPoint:point]];
  461. if (!result && self.extendsLinkTouchArea) {
  462. result = [self linkAtRadius:2.5f aroundPoint:point]
  463. ?: [self linkAtRadius:5.f aroundPoint:point]
  464. ?: [self linkAtRadius:7.5f aroundPoint:point]
  465. ?: [self linkAtRadius:12.5f aroundPoint:point]
  466. ?: [self linkAtRadius:15.f aroundPoint:point];
  467. }
  468. return result;
  469. }
  470. - (TTTAttributedLabelLink *)linkAtRadius:(const CGFloat)radius aroundPoint:(CGPoint)point {
  471. const CGFloat diagonal = CGFloat_sqrt(2 * radius * radius);
  472. const CGPoint deltas[] = {
  473. CGPointMake(0, -radius), CGPointMake(0, radius), // Above and below
  474. CGPointMake(-radius, 0), CGPointMake(radius, 0), // Beside
  475. CGPointMake(-diagonal, -diagonal), CGPointMake(-diagonal, diagonal),
  476. CGPointMake(diagonal, diagonal), CGPointMake(diagonal, -diagonal) // Diagonal
  477. };
  478. const size_t count = sizeof(deltas) / sizeof(CGPoint);
  479. TTTAttributedLabelLink *link = nil;
  480. for (NSUInteger i = 0; i < count && link.result == nil; i ++) {
  481. CGPoint currentPoint = CGPointMake(point.x + deltas[i].x, point.y + deltas[i].y);
  482. link = [self linkAtCharacterIndex:[self characterIndexAtPoint:currentPoint]];
  483. }
  484. return link;
  485. }
  486. - (TTTAttributedLabelLink *)linkAtCharacterIndex:(CFIndex)idx {
  487. // Do not enumerate if the index is outside of the bounds of the text.
  488. if (!NSLocationInRange((NSUInteger)idx, NSMakeRange(0, self.attributedText.length))) {
  489. return nil;
  490. }
  491. NSEnumerator *enumerator = [self.linkModels reverseObjectEnumerator];
  492. TTTAttributedLabelLink *link = nil;
  493. while ((link = [enumerator nextObject])) {
  494. if (NSLocationInRange((NSUInteger)idx, link.result.range)) {
  495. return link;
  496. }
  497. }
  498. return nil;
  499. }
  500. - (CFIndex)characterIndexAtPoint:(CGPoint)p {
  501. if (!CGRectContainsPoint(self.bounds, p)) {
  502. return NSNotFound;
  503. }
  504. CGRect textRect = [self textRectForBounds:self.bounds limitedToNumberOfLines:self.numberOfLines];
  505. if (!CGRectContainsPoint(textRect, p)) {
  506. return NSNotFound;
  507. }
  508. // Offset tap coordinates by textRect origin to make them relative to the origin of frame
  509. p = CGPointMake(p.x - textRect.origin.x, p.y - textRect.origin.y);
  510. // Convert tap coordinates (start at top left) to CT coordinates (start at bottom left)
  511. p = CGPointMake(p.x, textRect.size.height - p.y);
  512. CGMutablePathRef path = CGPathCreateMutable();
  513. CGPathAddRect(path, NULL, textRect);
  514. CTFrameRef frame = CTFramesetterCreateFrame([self framesetter], CFRangeMake(0, (CFIndex)[self.attributedText length]), path, NULL);
  515. if (frame == NULL) {
  516. CGPathRelease(path);
  517. return NSNotFound;
  518. }
  519. CFArrayRef lines = CTFrameGetLines(frame);
  520. NSInteger numberOfLines = self.numberOfLines > 0 ? MIN(self.numberOfLines, CFArrayGetCount(lines)) : CFArrayGetCount(lines);
  521. if (numberOfLines == 0) {
  522. CFRelease(frame);
  523. CGPathRelease(path);
  524. return NSNotFound;
  525. }
  526. CFIndex idx = NSNotFound;
  527. CGPoint lineOrigins[numberOfLines];
  528. CTFrameGetLineOrigins(frame, CFRangeMake(0, numberOfLines), lineOrigins);
  529. for (CFIndex lineIndex = 0; lineIndex < numberOfLines; lineIndex++) {
  530. CGPoint lineOrigin = lineOrigins[lineIndex];
  531. CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex);
  532. // Get bounding information of line
  533. CGFloat ascent = 0.0f, descent = 0.0f, leading = 0.0f;
  534. CGFloat width = (CGFloat)CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
  535. CGFloat yMin = (CGFloat)floor(lineOrigin.y - descent);
  536. CGFloat yMax = (CGFloat)ceil(lineOrigin.y + ascent);
  537. // Apply penOffset using flushFactor for horizontal alignment to set lineOrigin since this is the horizontal offset from drawFramesetter
  538. CGFloat flushFactor = TTTFlushFactorForTextAlignment(self.textAlignment);
  539. CGFloat penOffset = (CGFloat)CTLineGetPenOffsetForFlush(line, flushFactor, textRect.size.width);
  540. lineOrigin.x = penOffset;
  541. // Check if we've already passed the line
  542. if (p.y > yMax) {
  543. break;
  544. }
  545. // Check if the point is within this line vertically
  546. if (p.y >= yMin) {
  547. // Check if the point is within this line horizontally
  548. if (p.x >= lineOrigin.x && p.x <= lineOrigin.x + width) {
  549. // Convert CT coordinates to line-relative coordinates
  550. CGPoint relativePoint = CGPointMake(p.x - lineOrigin.x, p.y - lineOrigin.y);
  551. idx = CTLineGetStringIndexForPosition(line, relativePoint);
  552. break;
  553. }
  554. }
  555. }
  556. CFRelease(frame);
  557. CGPathRelease(path);
  558. return idx;
  559. }
  560. - (CGRect)boundingRectForCharacterRange:(NSRange)range {
  561. NSMutableAttributedString *mutableAttributedString = [self.attributedText mutableCopy];
  562. NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:mutableAttributedString];
  563. NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
  564. [textStorage addLayoutManager:layoutManager];
  565. NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:self.bounds.size];
  566. [layoutManager addTextContainer:textContainer];
  567. NSRange glyphRange;
  568. [layoutManager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange];
  569. return [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer];
  570. }
  571. - (void)drawFramesetter:(CTFramesetterRef)framesetter
  572. attributedString:(NSAttributedString *)attributedString
  573. textRange:(CFRange)textRange
  574. inRect:(CGRect)rect
  575. context:(CGContextRef)c
  576. {
  577. CGMutablePathRef path = CGPathCreateMutable();
  578. CGPathAddRect(path, NULL, rect);
  579. CTFrameRef frame = CTFramesetterCreateFrame(framesetter, textRange, path, NULL);
  580. [self drawBackground:frame inRect:rect context:c];
  581. CFArrayRef lines = CTFrameGetLines(frame);
  582. NSInteger numberOfLines = self.numberOfLines > 0 ? MIN(self.numberOfLines, CFArrayGetCount(lines)) : CFArrayGetCount(lines);
  583. BOOL truncateLastLine = (self.lineBreakMode == TTTLineBreakByTruncatingHead || self.lineBreakMode == TTTLineBreakByTruncatingMiddle || self.lineBreakMode == TTTLineBreakByTruncatingTail);
  584. CGPoint lineOrigins[numberOfLines];
  585. CTFrameGetLineOrigins(frame, CFRangeMake(0, numberOfLines), lineOrigins);
  586. for (CFIndex lineIndex = 0; lineIndex < numberOfLines; lineIndex++) {
  587. CGPoint lineOrigin = lineOrigins[lineIndex];
  588. CGContextSetTextPosition(c, lineOrigin.x, lineOrigin.y);
  589. CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex);
  590. CGFloat descent = 0.0f;
  591. CTLineGetTypographicBounds((CTLineRef)line, NULL, &descent, NULL);
  592. // Adjust pen offset for flush depending on text alignment
  593. CGFloat flushFactor = TTTFlushFactorForTextAlignment(self.textAlignment);
  594. if (lineIndex == numberOfLines - 1 && truncateLastLine) {
  595. // Check if the range of text in the last line reaches the end of the full attributed string
  596. CFRange lastLineRange = CTLineGetStringRange(line);
  597. if (!(lastLineRange.length == 0 && lastLineRange.location == 0) && lastLineRange.location + lastLineRange.length < textRange.location + textRange.length) {
  598. // Get correct truncationType and attribute position
  599. CTLineTruncationType truncationType;
  600. CFIndex truncationAttributePosition = lastLineRange.location;
  601. TTTLineBreakMode lineBreakMode = self.lineBreakMode;
  602. // Multiple lines, only use UILineBreakModeTailTruncation
  603. if (numberOfLines != 1) {
  604. lineBreakMode = TTTLineBreakByTruncatingTail;
  605. }
  606. switch (lineBreakMode) {
  607. case TTTLineBreakByTruncatingHead:
  608. truncationType = kCTLineTruncationStart;
  609. break;
  610. case TTTLineBreakByTruncatingMiddle:
  611. truncationType = kCTLineTruncationMiddle;
  612. truncationAttributePosition += (lastLineRange.length / 2);
  613. break;
  614. case TTTLineBreakByTruncatingTail:
  615. default:
  616. truncationType = kCTLineTruncationEnd;
  617. truncationAttributePosition += (lastLineRange.length - 1);
  618. break;
  619. }
  620. NSAttributedString *attributedTruncationString = self.attributedTruncationToken;
  621. if (!attributedTruncationString) {
  622. NSString *truncationTokenString = @"\u2026"; // Unicode Character 'HORIZONTAL ELLIPSIS' (U+2026)
  623. NSDictionary *truncationTokenStringAttributes = truncationTokenStringAttributes = [attributedString attributesAtIndex:(NSUInteger)truncationAttributePosition effectiveRange:NULL];
  624. attributedTruncationString = [[NSAttributedString alloc] initWithString:truncationTokenString attributes:truncationTokenStringAttributes];
  625. }
  626. CTLineRef truncationToken = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)attributedTruncationString);
  627. // Append truncationToken to the string
  628. // because if string isn't too long, CT won't add the truncationToken on its own.
  629. // There is no chance of a double truncationToken because CT only adds the
  630. // token if it removes characters (and the one we add will go first)
  631. NSMutableAttributedString *truncationString = [[NSMutableAttributedString alloc] initWithAttributedString:
  632. [attributedString attributedSubstringFromRange:
  633. NSMakeRange((NSUInteger)lastLineRange.location,
  634. (NSUInteger)lastLineRange.length)]];
  635. if (lastLineRange.length > 0) {
  636. // Remove any newline at the end (we don't want newline space between the text and the truncation token). There can only be one, because the second would be on the next line.
  637. unichar lastCharacter = [[truncationString string] characterAtIndex:(NSUInteger)(lastLineRange.length - 1)];
  638. if ([[NSCharacterSet newlineCharacterSet] characterIsMember:lastCharacter]) {
  639. [truncationString deleteCharactersInRange:NSMakeRange((NSUInteger)(lastLineRange.length - 1), 1)];
  640. }
  641. }
  642. [truncationString appendAttributedString:attributedTruncationString];
  643. CTLineRef truncationLine = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)truncationString);
  644. // Truncate the line in case it is too long.
  645. CTLineRef truncatedLine = CTLineCreateTruncatedLine(truncationLine, rect.size.width, truncationType, truncationToken);
  646. if (!truncatedLine) {
  647. // If the line is not as wide as the truncationToken, truncatedLine is NULL
  648. truncatedLine = CFRetain(truncationToken);
  649. }
  650. CGFloat penOffset = (CGFloat)CTLineGetPenOffsetForFlush(truncatedLine, flushFactor, rect.size.width);
  651. CGContextSetTextPosition(c, penOffset, lineOrigin.y - descent - self.font.descender);
  652. CTLineDraw(truncatedLine, c);
  653. NSRange linkRange;
  654. if ([attributedTruncationString attribute:NSLinkAttributeName atIndex:0 effectiveRange:&linkRange]) {
  655. NSRange tokenRange = [truncationString.string rangeOfString:attributedTruncationString.string];
  656. NSRange tokenLinkRange = NSMakeRange((NSUInteger)(lastLineRange.location+lastLineRange.length)-tokenRange.length, (NSUInteger)tokenRange.length);
  657. [self addLinkToURL:[attributedTruncationString attribute:NSLinkAttributeName atIndex:0 effectiveRange:&linkRange] withRange:tokenLinkRange];
  658. }
  659. CFRelease(truncatedLine);
  660. CFRelease(truncationLine);
  661. CFRelease(truncationToken);
  662. } else {
  663. CGFloat penOffset = (CGFloat)CTLineGetPenOffsetForFlush(line, flushFactor, rect.size.width);
  664. CGContextSetTextPosition(c, penOffset, lineOrigin.y - descent - self.font.descender);
  665. CTLineDraw(line, c);
  666. }
  667. } else {
  668. CGFloat penOffset = (CGFloat)CTLineGetPenOffsetForFlush(line, flushFactor, rect.size.width);
  669. CGContextSetTextPosition(c, penOffset, lineOrigin.y - descent - self.font.descender);
  670. CTLineDraw(line, c);
  671. }
  672. }
  673. [self drawStrike:frame inRect:rect context:c];
  674. CFRelease(frame);
  675. CGPathRelease(path);
  676. }
  677. - (void)drawBackground:(CTFrameRef)frame
  678. inRect:(CGRect)rect
  679. context:(CGContextRef)c
  680. {
  681. NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
  682. CGPoint origins[[lines count]];
  683. CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), origins);
  684. CFIndex lineIndex = 0;
  685. for (id line in lines) {
  686. CGFloat ascent = 0.0f, descent = 0.0f, leading = 0.0f;
  687. CGFloat width = (CGFloat)CTLineGetTypographicBounds((__bridge CTLineRef)line, &ascent, &descent, &leading) ;
  688. for (id glyphRun in (__bridge NSArray *)CTLineGetGlyphRuns((__bridge CTLineRef)line)) {
  689. NSDictionary *attributes = (__bridge NSDictionary *)CTRunGetAttributes((__bridge CTRunRef) glyphRun);
  690. CGColorRef strokeColor = CGColorRefFromColor([attributes objectForKey:kTTTBackgroundStrokeColorAttributeName]);
  691. CGColorRef fillColor = CGColorRefFromColor([attributes objectForKey:kTTTBackgroundFillColorAttributeName]);
  692. UIEdgeInsets fillPadding = [[attributes objectForKey:kTTTBackgroundFillPaddingAttributeName] UIEdgeInsetsValue];
  693. CGFloat cornerRadius = [[attributes objectForKey:kTTTBackgroundCornerRadiusAttributeName] floatValue];
  694. CGFloat lineWidth = [[attributes objectForKey:kTTTBackgroundLineWidthAttributeName] floatValue];
  695. if (strokeColor || fillColor) {
  696. CGRect runBounds = CGRectZero;
  697. CGFloat runAscent = 0.0f;
  698. CGFloat runDescent = 0.0f;
  699. runBounds.size.width = (CGFloat)CTRunGetTypographicBounds((__bridge CTRunRef)glyphRun, CFRangeMake(0, 0), &runAscent, &runDescent, NULL) + fillPadding.left + fillPadding.right;
  700. runBounds.size.height = runAscent + runDescent + fillPadding.top + fillPadding.bottom;
  701. CGFloat xOffset = 0.0f;
  702. CFRange glyphRange = CTRunGetStringRange((__bridge CTRunRef)glyphRun);
  703. switch (CTRunGetStatus((__bridge CTRunRef)glyphRun)) {
  704. case kCTRunStatusRightToLeft:
  705. xOffset = CTLineGetOffsetForStringIndex((__bridge CTLineRef)line, glyphRange.location + glyphRange.length, NULL);
  706. break;
  707. default:
  708. xOffset = CTLineGetOffsetForStringIndex((__bridge CTLineRef)line, glyphRange.location, NULL);
  709. break;
  710. }
  711. runBounds.origin.x = origins[lineIndex].x + rect.origin.x + xOffset - fillPadding.left - rect.origin.x;
  712. runBounds.origin.y = origins[lineIndex].y + rect.origin.y - fillPadding.bottom - rect.origin.y;
  713. runBounds.origin.y -= runDescent;
  714. // Don't draw higlightedLinkBackground too far to the right (but filling padding can extend line)
  715. if (CGRectGetWidth(runBounds) > width + fillPadding.left + fillPadding.right) {
  716. runBounds.size.width = width + fillPadding.left + fillPadding.right;
  717. }
  718. CGPathRef path = [[UIBezierPath bezierPathWithRoundedRect:CGRectInset(UIEdgeInsetsInsetRect(runBounds, self.linkBackgroundEdgeInset), lineWidth, lineWidth) cornerRadius:cornerRadius] CGPath];
  719. CGContextSetLineJoin(c, kCGLineJoinRound);
  720. if (fillColor) {
  721. CGContextSetFillColorWithColor(c, fillColor);
  722. CGContextAddPath(c, path);
  723. CGContextFillPath(c);
  724. }
  725. if (strokeColor) {
  726. CGContextSetStrokeColorWithColor(c, strokeColor);
  727. CGContextAddPath(c, path);
  728. CGContextStrokePath(c);
  729. }
  730. }
  731. }
  732. lineIndex++;
  733. }
  734. }
  735. - (void)drawStrike:(CTFrameRef)frame
  736. inRect:(__unused CGRect)rect
  737. context:(CGContextRef)c
  738. {
  739. NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
  740. CGPoint origins[[lines count]];
  741. CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), origins);
  742. CFIndex lineIndex = 0;
  743. for (id line in lines) {
  744. CGFloat ascent = 0.0f, descent = 0.0f, leading = 0.0f;
  745. CGFloat width = (CGFloat)CTLineGetTypographicBounds((__bridge CTLineRef)line, &ascent, &descent, &leading) ;
  746. for (id glyphRun in (__bridge NSArray *)CTLineGetGlyphRuns((__bridge CTLineRef)line)) {
  747. NSDictionary *attributes = (__bridge NSDictionary *)CTRunGetAttributes((__bridge CTRunRef) glyphRun);
  748. BOOL strikeOut = [[attributes objectForKey:kTTTStrikeOutAttributeName] boolValue];
  749. NSInteger superscriptStyle = [[attributes objectForKey:(id)kCTSuperscriptAttributeName] integerValue];
  750. if (strikeOut) {
  751. CGRect runBounds = CGRectZero;
  752. CGFloat runAscent = 0.0f;
  753. CGFloat runDescent = 0.0f;
  754. runBounds.size.width = (CGFloat)CTRunGetTypographicBounds((__bridge CTRunRef)glyphRun, CFRangeMake(0, 0), &runAscent, &runDescent, NULL);
  755. runBounds.size.height = runAscent + runDescent;
  756. CGFloat xOffset = 0.0f;
  757. CFRange glyphRange = CTRunGetStringRange((__bridge CTRunRef)glyphRun);
  758. switch (CTRunGetStatus((__bridge CTRunRef)glyphRun)) {
  759. case kCTRunStatusRightToLeft:
  760. xOffset = CTLineGetOffsetForStringIndex((__bridge CTLineRef)line, glyphRange.location + glyphRange.length, NULL);
  761. break;
  762. default:
  763. xOffset = CTLineGetOffsetForStringIndex((__bridge CTLineRef)line, glyphRange.location, NULL);
  764. break;
  765. }
  766. runBounds.origin.x = origins[lineIndex].x + xOffset;
  767. runBounds.origin.y = origins[lineIndex].y;
  768. runBounds.origin.y -= runDescent;
  769. // Don't draw strikeout too far to the right
  770. if (CGRectGetWidth(runBounds) > width) {
  771. runBounds.size.width = width;
  772. }
  773. switch (superscriptStyle) {
  774. case 1:
  775. runBounds.origin.y -= runAscent * 0.47f;
  776. break;
  777. case -1:
  778. runBounds.origin.y += runAscent * 0.25f;
  779. break;
  780. default:
  781. break;
  782. }
  783. /***** BEGIN THREEMA MODIFICATION: Use text color, or default to black *********/
  784. id color = [attributes objectForKey:(id)kCTForegroundColorAttributeName];
  785. if (color) {
  786. CGContextSetStrokeColorWithColor(c, CGColorRefFromColor(color));
  787. } else {
  788. id nscolor = [attributes objectForKey:@"NSColor"];
  789. if (nscolor) {
  790. CGContextSetStrokeColorWithColor(c, CGColorRefFromColor(nscolor));
  791. } else {
  792. CGContextSetGrayStrokeColor(c, 0.0f, 1.0);
  793. }
  794. }
  795. /***** END THREEMA MODIFICATION: Use text color, or default to black *********/
  796. CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)self.font.fontName, self.font.pointSize, NULL);
  797. CGContextSetLineWidth(c, CTFontGetUnderlineThickness(font));
  798. CFRelease(font);
  799. CGFloat y = CGFloat_round(runBounds.origin.y + runBounds.size.height / 2.0f);
  800. CGContextMoveToPoint(c, runBounds.origin.x, y);
  801. CGContextAddLineToPoint(c, runBounds.origin.x + runBounds.size.width, y);
  802. CGContextStrokePath(c);
  803. }
  804. }
  805. lineIndex++;
  806. }
  807. }
  808. #pragma mark - TTTAttributedLabel
  809. - (void)setText:(id)text {
  810. NSParameterAssert(!text || [text isKindOfClass:[NSAttributedString class]] || [text isKindOfClass:[NSString class]]);
  811. if ([text isKindOfClass:[NSString class]]) {
  812. [self setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:nil];
  813. return;
  814. }
  815. self.attributedText = text;
  816. self.activeLink = nil;
  817. self.linkModels = [NSArray array];
  818. if (text && self.attributedText && self.enabledTextCheckingTypes) {
  819. __weak __typeof(self)weakSelf = self;
  820. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  821. __strong __typeof(weakSelf)strongSelf = weakSelf;
  822. NSDataDetector *dataDetector = strongSelf.dataDetector;
  823. if (dataDetector && [dataDetector respondsToSelector:@selector(matchesInString:options:range:)]) {
  824. NSArray *results = [dataDetector matchesInString:[(NSAttributedString *)text string] options:0 range:NSMakeRange(0, [(NSAttributedString *)text length])];
  825. if ([results count] > 0) {
  826. dispatch_async(dispatch_get_main_queue(), ^{
  827. if ([[strongSelf.attributedText string] isEqualToString:[(NSAttributedString *)text string]]) {
  828. [strongSelf addLinksWithTextCheckingResults:results attributes:strongSelf.linkAttributes];
  829. }
  830. });
  831. }
  832. }
  833. });
  834. }
  835. [self.attributedText enumerateAttribute:NSLinkAttributeName inRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:^(id value, __unused NSRange range, __unused BOOL *stop) {
  836. if (value) {
  837. NSURL *URL = [value isKindOfClass:[NSString class]] ? [NSURL URLWithString:value] : value;
  838. [self addLinkToURL:URL withRange:range];
  839. }
  840. }];
  841. }
  842. - (void)setText:(id)text
  843. afterInheritingLabelAttributesAndConfiguringWithBlock:(NSMutableAttributedString * (^)(NSMutableAttributedString *mutableAttributedString))block
  844. {
  845. NSMutableAttributedString *mutableAttributedString = nil;
  846. if ([text isKindOfClass:[NSString class]]) {
  847. mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:text attributes:NSAttributedStringAttributesFromLabel(self)];
  848. } else {
  849. mutableAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:text];
  850. [mutableAttributedString addAttributes:NSAttributedStringAttributesFromLabel(self) range:NSMakeRange(0, [mutableAttributedString length])];
  851. }
  852. if (block) {
  853. mutableAttributedString = block(mutableAttributedString);
  854. }
  855. [self setText:mutableAttributedString];
  856. }
  857. - (void)setActiveLink:(TTTAttributedLabelLink *)activeLink {
  858. _activeLink = activeLink;
  859. NSDictionary *activeAttributes = activeLink.activeAttributes ?: self.activeLinkAttributes;
  860. if (_activeLink && activeAttributes.count > 0) {
  861. if (!self.inactiveAttributedText) {
  862. self.inactiveAttributedText = [self.attributedText copy];
  863. }
  864. NSMutableAttributedString *mutableAttributedString = [self.inactiveAttributedText mutableCopy];
  865. if (self.activeLink.result.range.length > 0 && NSLocationInRange(NSMaxRange(self.activeLink.result.range) - 1, NSMakeRange(0, [self.inactiveAttributedText length]))) {
  866. [mutableAttributedString addAttributes:activeAttributes range:self.activeLink.result.range];
  867. }
  868. self.attributedText = mutableAttributedString;
  869. [self setNeedsDisplay];
  870. [CATransaction flush];
  871. } else if (self.inactiveAttributedText) {
  872. self.attributedText = self.inactiveAttributedText;
  873. self.inactiveAttributedText = nil;
  874. [self setNeedsDisplay];
  875. }
  876. }
  877. - (void)setLinkAttributes:(NSDictionary *)linkAttributes {
  878. _linkAttributes = convertNSAttributedStringAttributesToCTAttributes(linkAttributes);
  879. }
  880. - (void)setActiveLinkAttributes:(NSDictionary *)activeLinkAttributes {
  881. _activeLinkAttributes = convertNSAttributedStringAttributesToCTAttributes(activeLinkAttributes);
  882. }
  883. - (void)setInactiveLinkAttributes:(NSDictionary *)inactiveLinkAttributes {
  884. _inactiveLinkAttributes = convertNSAttributedStringAttributesToCTAttributes(inactiveLinkAttributes);
  885. }
  886. #pragma mark - UILabel
  887. - (void)setHighlighted:(BOOL)highlighted {
  888. [super setHighlighted:highlighted];
  889. [self setNeedsDisplay];
  890. }
  891. // Fixes crash when loading from a UIStoryboard
  892. - (UIColor *)textColor {
  893. UIColor *color = [super textColor];
  894. if (!color) {
  895. color = [UIColor blackColor];
  896. }
  897. return color;
  898. }
  899. - (void)setTextColor:(UIColor *)textColor {
  900. UIColor *oldTextColor = self.textColor;
  901. [super setTextColor:textColor];
  902. // Redraw to allow any ColorFromContext attributes a chance to update
  903. if (textColor != oldTextColor) {
  904. [self setNeedsFramesetter];
  905. [self setNeedsDisplay];
  906. }
  907. }
  908. - (CGRect)textRectForBounds:(CGRect)bounds
  909. limitedToNumberOfLines:(NSInteger)numberOfLines
  910. {
  911. bounds = UIEdgeInsetsInsetRect(bounds, self.textInsets);
  912. if (!self.attributedText) {
  913. return [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
  914. }
  915. CGRect textRect = bounds;
  916. // Calculate height with a minimum of double the font pointSize, to ensure that CTFramesetterSuggestFrameSizeWithConstraints doesn't return CGSizeZero, as it would if textRect height is insufficient.
  917. textRect.size.height = MAX(self.font.lineHeight * MAX(2, numberOfLines), bounds.size.height);
  918. // Adjust the text to be in the center vertically, if the text size is smaller than bounds
  919. CGSize textSize = CTFramesetterSuggestFrameSizeWithConstraints([self framesetter], CFRangeMake(0, (CFIndex)[self.attributedText length]), NULL, textRect.size, NULL);
  920. textSize = CGSizeMake(CGFloat_ceil(textSize.width), CGFloat_ceil(textSize.height)); // Fix for iOS 4, CTFramesetterSuggestFrameSizeWithConstraints sometimes returns fractional sizes
  921. if (textSize.height < bounds.size.height) {
  922. CGFloat yOffset = 0.0f;
  923. switch (self.verticalAlignment) {
  924. case TTTAttributedLabelVerticalAlignmentCenter:
  925. yOffset = CGFloat_floor((bounds.size.height - textSize.height) / 2.0f);
  926. break;
  927. case TTTAttributedLabelVerticalAlignmentBottom:
  928. yOffset = bounds.size.height - textSize.height;
  929. break;
  930. case TTTAttributedLabelVerticalAlignmentTop:
  931. default:
  932. break;
  933. }
  934. textRect.origin.y += yOffset;
  935. }
  936. return textRect;
  937. }
  938. - (void)drawTextInRect:(CGRect)rect {
  939. CGRect insetRect = UIEdgeInsetsInsetRect(rect, self.textInsets);
  940. if (!self.attributedText) {
  941. [super drawTextInRect:insetRect];
  942. return;
  943. }
  944. NSAttributedString *originalAttributedText = nil;
  945. // Adjust the font size to fit width, if necessarry
  946. if (self.adjustsFontSizeToFitWidth && self.numberOfLines > 0) {
  947. // Framesetter could still be working with a resized version of the text;
  948. // need to reset so we start from the original font size.
  949. // See #393.
  950. [self setNeedsFramesetter];
  951. [self setNeedsDisplay];
  952. if ([self respondsToSelector:@selector(invalidateIntrinsicContentSize)]) {
  953. [self invalidateIntrinsicContentSize];
  954. }
  955. // Use infinite width to find the max width, which will be compared to availableWidth if needed.
  956. CGSize maxSize = (self.numberOfLines > 1) ? CGSizeMake(TTTFLOAT_MAX, TTTFLOAT_MAX) : CGSizeZero;
  957. CGFloat textWidth = [self sizeThatFits:maxSize].width;
  958. CGFloat availableWidth = self.frame.size.width * self.numberOfLines;
  959. if (self.numberOfLines > 1 && self.lineBreakMode == TTTLineBreakByWordWrapping) {
  960. textWidth *= kTTTLineBreakWordWrapTextWidthScalingFactor;
  961. }
  962. if (textWidth > availableWidth && textWidth > 0.0f) {
  963. originalAttributedText = [self.attributedText copy];
  964. CGFloat scaleFactor = availableWidth / textWidth;
  965. if ([self respondsToSelector:@selector(minimumScaleFactor)] && self.minimumScaleFactor > scaleFactor) {
  966. scaleFactor = self.minimumScaleFactor;
  967. }
  968. self.attributedText = NSAttributedStringByScalingFontSize(self.attributedText, scaleFactor);
  969. }
  970. }
  971. CGContextRef c = UIGraphicsGetCurrentContext();
  972. CGContextSaveGState(c);
  973. {
  974. CGContextSetTextMatrix(c, CGAffineTransformIdentity);
  975. // Inverts the CTM to match iOS coordinates (otherwise text draws upside-down; Mac OS's system is different)
  976. CGContextTranslateCTM(c, 0.0f, insetRect.size.height);
  977. CGContextScaleCTM(c, 1.0f, -1.0f);
  978. CFRange textRange = CFRangeMake(0, (CFIndex)[self.attributedText length]);
  979. // First, get the text rect (which takes vertical centering into account)
  980. CGRect textRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
  981. // CoreText draws its text aligned to the bottom, so we move the CTM here to take our vertical offsets into account
  982. CGContextTranslateCTM(c, insetRect.origin.x, insetRect.size.height - textRect.origin.y - textRect.size.height);
  983. // Second, trace the shadow before the actual text, if we have one
  984. if (self.shadowColor && !self.highlighted) {
  985. CGContextSetShadowWithColor(c, self.shadowOffset, self.shadowRadius, [self.shadowColor CGColor]);
  986. } else if (self.highlightedShadowColor) {
  987. CGContextSetShadowWithColor(c, self.highlightedShadowOffset, self.highlightedShadowRadius, [self.highlightedShadowColor CGColor]);
  988. }
  989. // Finally, draw the text or highlighted text itself (on top of the shadow, if there is one)
  990. if (self.highlightedTextColor && self.highlighted) {
  991. NSMutableAttributedString *highlightAttributedString = [self.renderedAttributedText mutableCopy];
  992. [highlightAttributedString addAttribute:(__bridge NSString *)kCTForegroundColorAttributeName value:(id)[self.highlightedTextColor CGColor] range:NSMakeRange(0, highlightAttributedString.length)];
  993. if (![self highlightFramesetter]) {
  994. CTFramesetterRef highlightFramesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)highlightAttributedString);
  995. [self setHighlightFramesetter:highlightFramesetter];
  996. CFRelease(highlightFramesetter);
  997. }
  998. [self drawFramesetter:[self highlightFramesetter] attributedString:highlightAttributedString textRange:textRange inRect:textRect context:c];
  999. } else {
  1000. [self drawFramesetter:[self framesetter] attributedString:self.renderedAttributedText textRange:textRange inRect:textRect context:c];
  1001. }
  1002. // If we adjusted the font size, set it back to its original size
  1003. if (originalAttributedText) {
  1004. // Use ivar directly to avoid clearing out framesetter and renderedAttributedText
  1005. _attributedText = originalAttributedText;
  1006. }
  1007. }
  1008. CGContextRestoreGState(c);
  1009. }
  1010. #pragma mark - UIAccessibilityElement
  1011. - (BOOL)isAccessibilityElement {
  1012. return NO;
  1013. }
  1014. - (NSInteger)accessibilityElementCount {
  1015. return (NSInteger)[[self accessibilityElements] count];
  1016. }
  1017. - (id)accessibilityElementAtIndex:(NSInteger)index {
  1018. return [[self accessibilityElements] objectAtIndex:(NSUInteger)index];
  1019. }
  1020. - (NSInteger)indexOfAccessibilityElement:(id)element {
  1021. return (NSInteger)[[self accessibilityElements] indexOfObject:element];
  1022. }
  1023. - (NSArray *)accessibilityElements {
  1024. if (!_accessibilityElements) {
  1025. @synchronized(self) {
  1026. NSMutableArray *mutableAccessibilityItems = [NSMutableArray array];
  1027. for (TTTAttributedLabelLink *link in self.linkModels) {
  1028. if (link.result.range.location == NSNotFound) {
  1029. continue;
  1030. }
  1031. NSString *sourceText = [self.text isKindOfClass:[NSString class]] ? self.text : [(NSAttributedString *)self.text string];
  1032. NSString *accessibilityLabel = [sourceText substringWithRange:link.result.range];
  1033. NSString *accessibilityValue = link.accessibilityValue;
  1034. if (accessibilityLabel) {
  1035. TTTAccessibilityElement *linkElement = [[TTTAccessibilityElement alloc] initWithAccessibilityContainer:self];
  1036. linkElement.accessibilityTraits = UIAccessibilityTraitLink;
  1037. linkElement.boundingRect = [self boundingRectForCharacterRange:link.result.range];
  1038. linkElement.superview = self;
  1039. linkElement.accessibilityLabel = accessibilityLabel;
  1040. if (![accessibilityLabel isEqualToString:accessibilityValue]) {
  1041. linkElement.accessibilityValue = accessibilityValue;
  1042. }
  1043. [mutableAccessibilityItems addObject:linkElement];
  1044. }
  1045. }
  1046. TTTAccessibilityElement *baseElement = [[TTTAccessibilityElement alloc] initWithAccessibilityContainer:self];
  1047. baseElement.accessibilityLabel = [super accessibilityLabel];
  1048. baseElement.accessibilityHint = [super accessibilityHint];
  1049. baseElement.accessibilityValue = [super accessibilityValue];
  1050. baseElement.boundingRect = self.bounds;
  1051. baseElement.superview = self;
  1052. baseElement.accessibilityTraits = [super accessibilityTraits];
  1053. [mutableAccessibilityItems addObject:baseElement];
  1054. self.accessibilityElements = [NSArray arrayWithArray:mutableAccessibilityItems];
  1055. }
  1056. }
  1057. return _accessibilityElements;
  1058. }
  1059. #pragma mark - UIView
  1060. - (CGSize)sizeThatFits:(CGSize)size {
  1061. if (!self.attributedText) {
  1062. return [super sizeThatFits:size];
  1063. } else {
  1064. NSAttributedString *string = [self renderedAttributedText];
  1065. CGSize labelSize = CTFramesetterSuggestFrameSizeForAttributedStringWithConstraints([self framesetter], string, size, (NSUInteger)self.numberOfLines);
  1066. labelSize.width += self.textInsets.left + self.textInsets.right;
  1067. labelSize.height += self.textInsets.top + self.textInsets.bottom;
  1068. return labelSize;
  1069. }
  1070. }
  1071. - (CGSize)intrinsicContentSize {
  1072. // There's an implicit width from the original UILabel implementation
  1073. return [self sizeThatFits:[super intrinsicContentSize]];
  1074. }
  1075. - (void)tintColorDidChange {
  1076. if (!self.inactiveLinkAttributes || [self.inactiveLinkAttributes count] == 0) {
  1077. return;
  1078. }
  1079. BOOL isInactive = (self.tintAdjustmentMode == UIViewTintAdjustmentModeDimmed);
  1080. NSMutableAttributedString *mutableAttributedString = [self.attributedText mutableCopy];
  1081. for (TTTAttributedLabelLink *link in self.linkModels) {
  1082. NSDictionary *attributesToRemove = isInactive ? link.attributes : link.inactiveAttributes;
  1083. NSDictionary *attributesToAdd = isInactive ? link.inactiveAttributes : link.attributes;
  1084. [attributesToRemove enumerateKeysAndObjectsUsingBlock:^(NSString *name, __unused id value, __unused BOOL *stop) {
  1085. if (NSMaxRange(link.result.range) <= mutableAttributedString.length) {
  1086. [mutableAttributedString removeAttribute:name range:link.result.range];
  1087. }
  1088. }];
  1089. if (attributesToAdd) {
  1090. if (NSMaxRange(link.result.range) <= mutableAttributedString.length) {
  1091. [mutableAttributedString addAttributes:attributesToAdd range:link.result.range];
  1092. }
  1093. }
  1094. }
  1095. self.attributedText = mutableAttributedString;
  1096. [self setNeedsDisplay];
  1097. }
  1098. - (UIView *)hitTest:(CGPoint)point
  1099. withEvent:(UIEvent *)event
  1100. {
  1101. if (![self linkAtPoint:point] || !self.userInteractionEnabled || self.hidden || self.alpha < 0.01) {
  1102. return [super hitTest:point withEvent:event];
  1103. }
  1104. return self;
  1105. }
  1106. #pragma mark - UIResponder
  1107. - (BOOL)canBecomeFirstResponder {
  1108. return YES;
  1109. }
  1110. - (BOOL)canPerformAction:(SEL)action
  1111. withSender:(__unused id)sender
  1112. {
  1113. #if !TARGET_OS_TV
  1114. return (action == @selector(copy:));
  1115. #else
  1116. return NO;
  1117. #endif
  1118. }
  1119. - (void)touchesBegan:(NSSet *)touches
  1120. withEvent:(UIEvent *)event
  1121. {
  1122. UITouch *touch = [touches anyObject];
  1123. self.activeLink = [self linkAtPoint:[touch locationInView:self]];
  1124. if (!self.activeLink) {
  1125. [super touchesBegan:touches withEvent:event];
  1126. }
  1127. }
  1128. - (void)touchesMoved:(NSSet *)touches
  1129. withEvent:(UIEvent *)event
  1130. {
  1131. if (self.activeLink) {
  1132. UITouch *touch = [touches anyObject];
  1133. if (self.activeLink != [self linkAtPoint:[touch locationInView:self]]) {
  1134. self.activeLink = nil;
  1135. }
  1136. } else {
  1137. [super touchesMoved:touches withEvent:event];
  1138. }
  1139. }
  1140. - (void)touchesEnded:(NSSet *)touches
  1141. withEvent:(UIEvent *)event
  1142. {
  1143. if (self.activeLink) {
  1144. if (self.activeLink.linkTapBlock) {
  1145. self.activeLink.linkTapBlock(self, self.activeLink);
  1146. self.activeLink = nil;
  1147. return;
  1148. }
  1149. NSTextCheckingResult *result = self.activeLink.result;
  1150. self.activeLink = nil;
  1151. switch (result.resultType) {
  1152. case NSTextCheckingTypeLink:
  1153. if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithURL:)]) {
  1154. [self.delegate attributedLabel:self didSelectLinkWithURL:result.URL];
  1155. return;
  1156. }
  1157. break;
  1158. case NSTextCheckingTypeAddress:
  1159. if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithAddress:)]) {
  1160. [self.delegate attributedLabel:self didSelectLinkWithAddress:result.addressComponents];
  1161. return;
  1162. }
  1163. break;
  1164. case NSTextCheckingTypePhoneNumber:
  1165. if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithPhoneNumber:)]) {
  1166. [self.delegate attributedLabel:self didSelectLinkWithPhoneNumber:result.phoneNumber];
  1167. return;
  1168. }
  1169. break;
  1170. case NSTextCheckingTypeDate:
  1171. if (result.timeZone && [self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithDate:timeZone:duration:)]) {
  1172. [self.delegate attributedLabel:self didSelectLinkWithDate:result.date timeZone:result.timeZone duration:result.duration];
  1173. return;
  1174. } else if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithDate:)]) {
  1175. [self.delegate attributedLabel:self didSelectLinkWithDate:result.date];
  1176. return;
  1177. }
  1178. break;
  1179. case NSTextCheckingTypeTransitInformation:
  1180. if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithTransitInformation:)]) {
  1181. [self.delegate attributedLabel:self didSelectLinkWithTransitInformation:result.components];
  1182. return;
  1183. }
  1184. default:
  1185. break;
  1186. }
  1187. // Fallback to `attributedLabel:didSelectLinkWithTextCheckingResult:` if no other delegate method matched.
  1188. if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithTextCheckingResult:)]) {
  1189. [self.delegate attributedLabel:self didSelectLinkWithTextCheckingResult:result];
  1190. }
  1191. } else {
  1192. [super touchesEnded:touches withEvent:event];
  1193. }
  1194. }
  1195. - (void)touchesCancelled:(NSSet *)touches
  1196. withEvent:(UIEvent *)event
  1197. {
  1198. if (self.activeLink) {
  1199. self.activeLink = nil;
  1200. } else {
  1201. [super touchesCancelled:touches withEvent:event];
  1202. }
  1203. }
  1204. #pragma mark - UIGestureRecognizerDelegate
  1205. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
  1206. return [self containslinkAtPoint:[touch locationInView:self]];
  1207. }
  1208. #pragma mark - UILongPressGestureRecognizer
  1209. - (void)longPressGestureDidFire:(UILongPressGestureRecognizer *)sender {
  1210. switch (sender.state) {
  1211. case UIGestureRecognizerStateBegan: {
  1212. CGPoint touchPoint = [sender locationInView:self];
  1213. TTTAttributedLabelLink *link = [self linkAtPoint:touchPoint];
  1214. if (link) {
  1215. if (link.linkLongPressBlock) {
  1216. link.linkLongPressBlock(self, link);
  1217. return;
  1218. }
  1219. NSTextCheckingResult *result = link.result;
  1220. if (!result) {
  1221. return;
  1222. }
  1223. switch (result.resultType) {
  1224. case NSTextCheckingTypeLink:
  1225. if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithURL:atPoint:)]) {
  1226. [self.delegate attributedLabel:self didLongPressLinkWithURL:result.URL atPoint:touchPoint];
  1227. return;
  1228. }
  1229. break;
  1230. case NSTextCheckingTypeAddress:
  1231. if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithAddress:atPoint:)]) {
  1232. [self.delegate attributedLabel:self didLongPressLinkWithAddress:result.addressComponents atPoint:touchPoint];
  1233. return;
  1234. }
  1235. break;
  1236. case NSTextCheckingTypePhoneNumber:
  1237. if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithPhoneNumber:atPoint:)]) {
  1238. [self.delegate attributedLabel:self didLongPressLinkWithPhoneNumber:result.phoneNumber atPoint:touchPoint];
  1239. return;
  1240. }
  1241. break;
  1242. case NSTextCheckingTypeDate:
  1243. if (result.timeZone && [self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithDate:timeZone:duration:atPoint:)]) {
  1244. [self.delegate attributedLabel:self didLongPressLinkWithDate:result.date timeZone:result.timeZone duration:result.duration atPoint:touchPoint];
  1245. return;
  1246. } else if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithDate:atPoint:)]) {
  1247. [self.delegate attributedLabel:self didLongPressLinkWithDate:result.date atPoint:touchPoint];
  1248. return;
  1249. }
  1250. break;
  1251. case NSTextCheckingTypeTransitInformation:
  1252. if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithTransitInformation:atPoint:)]) {
  1253. [self.delegate attributedLabel:self didLongPressLinkWithTransitInformation:result.components atPoint:touchPoint];
  1254. return;
  1255. }
  1256. default:
  1257. break;
  1258. }
  1259. // Fallback to `attributedLabel:didLongPressLinkWithTextCheckingResult:atPoint:` if no other delegate method matched.
  1260. if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithTextCheckingResult:atPoint:)]) {
  1261. [self.delegate attributedLabel:self didLongPressLinkWithTextCheckingResult:result atPoint:touchPoint];
  1262. }
  1263. }
  1264. break;
  1265. }
  1266. default:
  1267. break;
  1268. }
  1269. }
  1270. #if !TARGET_OS_TV
  1271. #pragma mark - UIResponderStandardEditActions
  1272. - (void)copy:(__unused id)sender {
  1273. [[UIPasteboard generalPasteboard] setString:self.text];
  1274. }
  1275. #endif
  1276. #pragma mark - NSCoding
  1277. - (void)encodeWithCoder:(NSCoder *)coder {
  1278. [super encodeWithCoder:coder];
  1279. [coder encodeObject:@(self.enabledTextCheckingTypes) forKey:NSStringFromSelector(@selector(enabledTextCheckingTypes))];
  1280. [coder encodeObject:self.linkModels forKey:NSStringFromSelector(@selector(linkModels))];
  1281. if ([NSMutableParagraphStyle class]) {
  1282. [coder encodeObject:self.linkAttributes forKey:NSStringFromSelector(@selector(linkAttributes))];
  1283. [coder encodeObject:self.activeLinkAttributes forKey:NSStringFromSelector(@selector(activeLinkAttributes))];
  1284. [coder encodeObject:self.inactiveLinkAttributes forKey:NSStringFromSelector(@selector(inactiveLinkAttributes))];
  1285. }
  1286. [coder encodeObject:@(self.shadowRadius) forKey:NSStringFromSelector(@selector(shadowRadius))];
  1287. [coder encodeObject:@(self.highlightedShadowRadius) forKey:NSStringFromSelector(@selector(highlightedShadowRadius))];
  1288. [coder encodeCGSize:self.highlightedShadowOffset forKey:NSStringFromSelector(@selector(highlightedShadowOffset))];
  1289. [coder encodeObject:self.highlightedShadowColor forKey:NSStringFromSelector(@selector(highlightedShadowColor))];
  1290. [coder encodeObject:@(self.kern) forKey:NSStringFromSelector(@selector(kern))];
  1291. [coder encodeObject:@(self.firstLineIndent) forKey:NSStringFromSelector(@selector(firstLineIndent))];
  1292. [coder encodeObject:@(self.lineSpacing) forKey:NSStringFromSelector(@selector(lineSpacing))];
  1293. [coder encodeObject:@(self.lineHeightMultiple) forKey:NSStringFromSelector(@selector(lineHeightMultiple))];
  1294. [coder encodeUIEdgeInsets:self.textInsets forKey:NSStringFromSelector(@selector(textInsets))];
  1295. [coder encodeInteger:self.verticalAlignment forKey:NSStringFromSelector(@selector(verticalAlignment))];
  1296. [coder encodeObject:self.attributedTruncationToken forKey:NSStringFromSelector(@selector(attributedTruncationToken))];
  1297. [coder encodeObject:NSStringFromUIEdgeInsets(self.linkBackgroundEdgeInset) forKey:NSStringFromSelector(@selector(linkBackgroundEdgeInset))];
  1298. [coder encodeObject:self.attributedText forKey:NSStringFromSelector(@selector(attributedText))];
  1299. [coder encodeObject:self.text forKey:NSStringFromSelector(@selector(text))];
  1300. }
  1301. - (id)initWithCoder:(NSCoder *)coder {
  1302. self = [super initWithCoder:coder];
  1303. if (!self) {
  1304. return nil;
  1305. }
  1306. [self commonInit];
  1307. if ([coder containsValueForKey:NSStringFromSelector(@selector(enabledTextCheckingTypes))]) {
  1308. self.enabledTextCheckingTypes = [[coder decodeObjectForKey:NSStringFromSelector(@selector(enabledTextCheckingTypes))] unsignedLongLongValue];
  1309. }
  1310. if ([NSMutableParagraphStyle class]) {
  1311. if ([coder containsValueForKey:NSStringFromSelector(@selector(linkAttributes))]) {
  1312. self.linkAttributes = [coder decodeObjectForKey:NSStringFromSelector(@selector(linkAttributes))];
  1313. }
  1314. if ([coder containsValueForKey:NSStringFromSelector(@selector(activeLinkAttributes))]) {
  1315. self.activeLinkAttributes = [coder decodeObjectForKey:NSStringFromSelector(@selector(activeLinkAttributes))];
  1316. }
  1317. if ([coder containsValueForKey:NSStringFromSelector(@selector(inactiveLinkAttributes))]) {
  1318. self.inactiveLinkAttributes = [coder decodeObjectForKey:NSStringFromSelector(@selector(inactiveLinkAttributes))];
  1319. }
  1320. }
  1321. if ([coder containsValueForKey:NSStringFromSelector(@selector(links))]) {
  1322. NSArray *oldLinks = [coder decodeObjectForKey:NSStringFromSelector(@selector(links))];
  1323. [self addLinksWithTextCheckingResults:oldLinks attributes:nil];
  1324. }
  1325. if ([coder containsValueForKey:NSStringFromSelector(@selector(linkModels))]) {
  1326. self.linkModels = [coder decodeObjectForKey:NSStringFromSelector(@selector(linkModels))];
  1327. }
  1328. if ([coder containsValueForKey:NSStringFromSelector(@selector(shadowRadius))]) {
  1329. self.shadowRadius = [[coder decodeObjectForKey:NSStringFromSelector(@selector(shadowRadius))] floatValue];
  1330. }
  1331. if ([coder containsValueForKey:NSStringFromSelector(@selector(highlightedShadowRadius))]) {
  1332. self.highlightedShadowRadius = [[coder decodeObjectForKey:NSStringFromSelector(@selector(highlightedShadowRadius))] floatValue];
  1333. }
  1334. if ([coder containsValueForKey:NSStringFromSelector(@selector(highlightedShadowOffset))]) {
  1335. self.highlightedShadowOffset = [coder decodeCGSizeForKey:NSStringFromSelector(@selector(highlightedShadowOffset))];
  1336. }
  1337. if ([coder containsValueForKey:NSStringFromSelector(@selector(highlightedShadowColor))]) {
  1338. self.highlightedShadowColor = [coder decodeObjectForKey:NSStringFromSelector(@selector(highlightedShadowColor))];
  1339. }
  1340. if ([coder containsValueForKey:NSStringFromSelector(@selector(kern))]) {
  1341. self.kern = [[coder decodeObjectForKey:NSStringFromSelector(@selector(kern))] floatValue];
  1342. }
  1343. if ([coder containsValueForKey:NSStringFromSelector(@selector(firstLineIndent))]) {
  1344. self.firstLineIndent = [[coder decodeObjectForKey:NSStringFromSelector(@selector(firstLineIndent))] floatValue];
  1345. }
  1346. if ([coder containsValueForKey:NSStringFromSelector(@selector(lineSpacing))]) {
  1347. self.lineSpacing = [[coder decodeObjectForKey:NSStringFromSelector(@selector(lineSpacing))] floatValue];
  1348. }
  1349. if ([coder containsValueForKey:NSStringFromSelector(@selector(minimumLineHeight))]) {
  1350. self.minimumLineHeight = [[coder decodeObjectForKey:NSStringFromSelector(@selector(minimumLineHeight))] floatValue];
  1351. }
  1352. if ([coder containsValueForKey:NSStringFromSelector(@selector(maximumLineHeight))]) {
  1353. self.maximumLineHeight = [[coder decodeObjectForKey:NSStringFromSelector(@selector(maximumLineHeight))] floatValue];
  1354. }
  1355. if ([coder containsValueForKey:NSStringFromSelector(@selector(lineHeightMultiple))]) {
  1356. self.lineHeightMultiple = [[coder decodeObjectForKey:NSStringFromSelector(@selector(lineHeightMultiple))] floatValue];
  1357. }
  1358. if ([coder containsValueForKey:NSStringFromSelector(@selector(textInsets))]) {
  1359. self.textInsets = [coder decodeUIEdgeInsetsForKey:NSStringFromSelector(@selector(textInsets))];
  1360. }
  1361. if ([coder containsValueForKey:NSStringFromSelector(@selector(verticalAlignment))]) {
  1362. self.verticalAlignment = [coder decodeIntegerForKey:NSStringFromSelector(@selector(verticalAlignment))];
  1363. }
  1364. if ([coder containsValueForKey:NSStringFromSelector(@selector(attributedTruncationToken))]) {
  1365. self.attributedTruncationToken = [coder decodeObjectForKey:NSStringFromSelector(@selector(attributedTruncationToken))];
  1366. }
  1367. if ([coder containsValueForKey:NSStringFromSelector(@selector(linkBackgroundEdgeInset))]) {
  1368. self.linkBackgroundEdgeInset = UIEdgeInsetsFromString([coder decodeObjectForKey:NSStringFromSelector(@selector(linkBackgroundEdgeInset))]);
  1369. }
  1370. if ([coder containsValueForKey:NSStringFromSelector(@selector(attributedText))]) {
  1371. self.attributedText = [coder decodeObjectForKey:NSStringFromSelector(@selector(attributedText))];
  1372. } else {
  1373. self.text = super.text;
  1374. }
  1375. return self;
  1376. }
  1377. @end
  1378. #pragma mark - TTTAttributedLabelLink
  1379. @implementation TTTAttributedLabelLink
  1380. - (instancetype)initWithAttributes:(NSDictionary *)attributes
  1381. activeAttributes:(NSDictionary *)activeAttributes
  1382. inactiveAttributes:(NSDictionary *)inactiveAttributes
  1383. textCheckingResult:(NSTextCheckingResult *)result {
  1384. if ((self = [super init])) {
  1385. _result = result;
  1386. _attributes = [attributes copy];
  1387. _activeAttributes = [activeAttributes copy];
  1388. _inactiveAttributes = [inactiveAttributes copy];
  1389. }
  1390. return self;
  1391. }
  1392. - (instancetype)initWithAttributesFromLabel:(TTTAttributedLabel*)label
  1393. textCheckingResult:(NSTextCheckingResult *)result {
  1394. return [self initWithAttributes:label.linkAttributes
  1395. activeAttributes:label.activeLinkAttributes
  1396. inactiveAttributes:label.inactiveLinkAttributes
  1397. textCheckingResult:result];
  1398. }
  1399. #pragma mark - Accessibility
  1400. - (NSString *) accessibilityValue {
  1401. if ([_accessibilityValue length] == 0) {
  1402. switch (self.result.resultType) {
  1403. case NSTextCheckingTypeLink:
  1404. _accessibilityValue = self.result.URL.absoluteString;
  1405. break;
  1406. case NSTextCheckingTypePhoneNumber:
  1407. _accessibilityValue = self.result.phoneNumber;
  1408. break;
  1409. case NSTextCheckingTypeDate:
  1410. _accessibilityValue = [NSDateFormatter localizedStringFromDate:self.result.date
  1411. dateStyle:NSDateFormatterLongStyle
  1412. timeStyle:NSDateFormatterLongStyle];
  1413. break;
  1414. default:
  1415. break;
  1416. }
  1417. }
  1418. return _accessibilityValue;
  1419. }
  1420. #pragma mark - NSCoding
  1421. - (void)encodeWithCoder:(NSCoder *)aCoder {
  1422. [aCoder encodeObject:self.result forKey:NSStringFromSelector(@selector(result))];
  1423. [aCoder encodeObject:self.attributes forKey:NSStringFromSelector(@selector(attributes))];
  1424. [aCoder encodeObject:self.activeAttributes forKey:NSStringFromSelector(@selector(activeAttributes))];
  1425. [aCoder encodeObject:self.inactiveAttributes forKey:NSStringFromSelector(@selector(inactiveAttributes))];
  1426. [aCoder encodeObject:self.accessibilityValue forKey:NSStringFromSelector(@selector(accessibilityValue))];
  1427. }
  1428. - (id)initWithCoder:(NSCoder *)aDecoder {
  1429. if ((self = [super init])) {
  1430. _result = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(result))];
  1431. _attributes = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(attributes))];
  1432. _activeAttributes = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(activeAttributes))];
  1433. _inactiveAttributes = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(inactiveAttributes))];
  1434. self.accessibilityValue = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(accessibilityValue))];
  1435. }
  1436. return self;
  1437. }
  1438. @end
  1439. #pragma mark -
  1440. static inline CGColorRef CGColorRefFromColor(id color) {
  1441. return [color isKindOfClass:[UIColor class]] ? [color CGColor] : (__bridge CGColorRef)color;
  1442. }
  1443. static inline CTFontRef CTFontRefFromUIFont(UIFont * font) {
  1444. CTFontRef ctfont = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);
  1445. return CFAutorelease(ctfont);
  1446. }
  1447. static inline NSDictionary * convertNSAttributedStringAttributesToCTAttributes(NSDictionary *attributes) {
  1448. if (!attributes) return nil;
  1449. NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionary];
  1450. NSDictionary *NSToCTAttributeNamesMap = @{
  1451. NSFontAttributeName: (NSString *)kCTFontAttributeName,
  1452. NSBackgroundColorAttributeName: (NSString *)kTTTBackgroundFillColorAttributeName,
  1453. NSForegroundColorAttributeName: (NSString *)kCTForegroundColorAttributeName,
  1454. NSUnderlineColorAttributeName: (NSString *)kCTUnderlineColorAttributeName,
  1455. NSUnderlineStyleAttributeName: (NSString *)kCTUnderlineStyleAttributeName,
  1456. NSStrokeWidthAttributeName: (NSString *)kCTStrokeWidthAttributeName,
  1457. NSStrokeColorAttributeName: (NSString *)kCTStrokeWidthAttributeName,
  1458. NSKernAttributeName: (NSString *)kCTKernAttributeName,
  1459. NSLigatureAttributeName: (NSString *)kCTLigatureAttributeName
  1460. };
  1461. [attributes enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
  1462. key = [NSToCTAttributeNamesMap objectForKey:key] ? : key;
  1463. if (![NSMutableParagraphStyle class]) {
  1464. if ([value isKindOfClass:[UIFont class]]) {
  1465. value = (__bridge id)CTFontRefFromUIFont(value);
  1466. } else if ([value isKindOfClass:[UIColor class]]) {
  1467. value = (__bridge id)((UIColor *)value).CGColor;
  1468. }
  1469. }
  1470. [mutableAttributes setObject:value forKey:key];
  1471. }];
  1472. return [NSDictionary dictionaryWithDictionary:mutableAttributes];
  1473. }