1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888 |
- // TTTAttributedLabel.m
- //
- // Copyright (c) 2011 Mattt Thompson (http://mattt.me)
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to deal
- // in the Software without restriction, including without limitation the rights
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- // copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- // THE SOFTWARE.
- #import "TTTAttributedLabel.h"
- #import <QuartzCore/QuartzCore.h>
- #import <Availability.h>
- #import <objc/runtime.h>
- #define kTTTLineBreakWordWrapTextWidthScalingFactor (M_PI / M_E)
- static CGFloat const TTTFLOAT_MAX = 100000;
- NSString * const kTTTStrikeOutAttributeName = @"TTTStrikeOutAttribute";
- NSString * const kTTTBackgroundFillColorAttributeName = @"TTTBackgroundFillColor";
- NSString * const kTTTBackgroundFillPaddingAttributeName = @"TTTBackgroundFillPadding";
- NSString * const kTTTBackgroundStrokeColorAttributeName = @"TTTBackgroundStrokeColor";
- NSString * const kTTTBackgroundLineWidthAttributeName = @"TTTBackgroundLineWidth";
- NSString * const kTTTBackgroundCornerRadiusAttributeName = @"TTTBackgroundCornerRadius";
- #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 60000
- const NSTextAlignment TTTTextAlignmentLeft = NSTextAlignmentLeft;
- const NSTextAlignment TTTTextAlignmentCenter = NSTextAlignmentCenter;
- const NSTextAlignment TTTTextAlignmentRight = NSTextAlignmentRight;
- const NSTextAlignment TTTTextAlignmentJustified = NSTextAlignmentJustified;
- const NSTextAlignment TTTTextAlignmentNatural = NSTextAlignmentNatural;
- const NSLineBreakMode TTTLineBreakByWordWrapping = NSLineBreakByWordWrapping;
- const NSLineBreakMode TTTLineBreakByCharWrapping = NSLineBreakByCharWrapping;
- const NSLineBreakMode TTTLineBreakByClipping = NSLineBreakByClipping;
- const NSLineBreakMode TTTLineBreakByTruncatingHead = NSLineBreakByTruncatingHead;
- const NSLineBreakMode TTTLineBreakByTruncatingMiddle = NSLineBreakByTruncatingMiddle;
- const NSLineBreakMode TTTLineBreakByTruncatingTail = NSLineBreakByTruncatingTail;
- typedef NSTextAlignment TTTTextAlignment;
- typedef NSLineBreakMode TTTLineBreakMode;
- #else
- const UITextAlignment TTTTextAlignmentLeft = NSTextAlignmentLeft;
- const UITextAlignment TTTTextAlignmentCenter = NSTextAlignmentCenter;
- const UITextAlignment TTTTextAlignmentRight = NSTextAlignmentRight;
- const UITextAlignment TTTTextAlignmentJustified = NSTextAlignmentJustified;
- const UITextAlignment TTTTextAlignmentNatural = NSTextAlignmentNatural;
- const UITextAlignment TTTLineBreakByWordWrapping = NSLineBreakByWordWrapping;
- const UITextAlignment TTTLineBreakByCharWrapping = NSLineBreakByCharWrapping;
- const UITextAlignment TTTLineBreakByClipping = NSLineBreakByClipping;
- const UITextAlignment TTTLineBreakByTruncatingHead = NSLineBreakByTruncatingHead;
- const UITextAlignment TTTLineBreakByTruncatingMiddle = NSLineBreakByTruncatingMiddle;
- const UITextAlignment TTTLineBreakByTruncatingTail = NSLineBreakByTruncatingTail;
- typedef UITextAlignment TTTTextAlignment;
- typedef UILineBreakMode TTTLineBreakMode;
- #endif
- static inline CTTextAlignment CTTextAlignmentFromTTTTextAlignment(TTTTextAlignment alignment) {
- #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 60000
- switch (alignment) {
- case NSTextAlignmentLeft: return kCTLeftTextAlignment;
- case NSTextAlignmentCenter: return kCTCenterTextAlignment;
- case NSTextAlignmentRight: return kCTRightTextAlignment;
- default: return kCTNaturalTextAlignment;
- }
- #else
- switch (alignment) {
- case UITextAlignmentLeft: return kCTLeftTextAlignment;
- case UITextAlignmentCenter: return kCTCenterTextAlignment;
- case UITextAlignmentRight: return kCTRightTextAlignment;
- default: return kCTNaturalTextAlignment;
- }
- #endif
- }
- static inline CTLineBreakMode CTLineBreakModeFromTTTLineBreakMode(TTTLineBreakMode lineBreakMode) {
- #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 60000
- switch (lineBreakMode) {
- case NSLineBreakByWordWrapping: return kCTLineBreakByWordWrapping;
- case NSLineBreakByCharWrapping: return kCTLineBreakByCharWrapping;
- case NSLineBreakByClipping: return kCTLineBreakByClipping;
- case NSLineBreakByTruncatingHead: return kCTLineBreakByTruncatingHead;
- case NSLineBreakByTruncatingTail: return kCTLineBreakByTruncatingTail;
- case NSLineBreakByTruncatingMiddle: return kCTLineBreakByTruncatingMiddle;
- default: return 0;
- }
- #else
- return CTLineBreakModeFromUILineBreakMode(lineBreakMode);
- #endif
- }
- #if __IPHONE_OS_VERSION_MAX_ALLOWED < 60000
- static inline CTLineBreakMode CTLineBreakModeFromUILineBreakMode(UILineBreakMode lineBreakMode) {
- #pragma clang diagnostic push
- #pragma clang diagnostic ignored "-Wdeprecated-declarations"
- switch (lineBreakMode) {
- case UILineBreakModeWordWrap: return kCTLineBreakByWordWrapping;
- case UILineBreakModeCharacterWrap: return kCTLineBreakByCharWrapping;
- case UILineBreakModeClip: return kCTLineBreakByClipping;
- case UILineBreakModeHeadTruncation: return kCTLineBreakByTruncatingHead;
- case UILineBreakModeTailTruncation: return kCTLineBreakByTruncatingTail;
- case UILineBreakModeMiddleTruncation: return kCTLineBreakByTruncatingMiddle;
- default: return 0;
- }
- #pragma clang diagnostic pop
- }
- #endif
- static inline CGFLOAT_TYPE CGFloat_ceil(CGFLOAT_TYPE cgfloat) {
- #if CGFLOAT_IS_DOUBLE
- return ceil(cgfloat);
- #else
- return ceilf(cgfloat);
- #endif
- }
- static inline CGFLOAT_TYPE CGFloat_floor(CGFLOAT_TYPE cgfloat) {
- #if CGFLOAT_IS_DOUBLE
- return floor(cgfloat);
- #else
- return floorf(cgfloat);
- #endif
- }
- static inline CGFLOAT_TYPE CGFloat_round(CGFLOAT_TYPE cgfloat) {
- #if CGFLOAT_IS_DOUBLE
- return round(cgfloat);
- #else
- return roundf(cgfloat);
- #endif
- }
- static inline CGFLOAT_TYPE CGFloat_sqrt(CGFLOAT_TYPE cgfloat) {
- #if CGFLOAT_IS_DOUBLE
- return sqrt(cgfloat);
- #else
- return sqrtf(cgfloat);
- #endif
- }
- static inline CGFloat TTTFlushFactorForTextAlignment(NSTextAlignment textAlignment) {
- switch (textAlignment) {
- case TTTTextAlignmentCenter:
- return 0.5f;
- case TTTTextAlignmentRight:
- return 1.0f;
- case TTTTextAlignmentLeft:
- default:
- return 0.0f;
- }
- }
- static inline NSDictionary * NSAttributedStringAttributesFromLabel(TTTAttributedLabel *label) {
- NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionary];
- if ([NSMutableParagraphStyle class]) {
- [mutableAttributes setObject:label.font forKey:(NSString *)kCTFontAttributeName];
- [mutableAttributes setObject:label.textColor forKey:(NSString *)kCTForegroundColorAttributeName];
- [mutableAttributes setObject:@(label.kern) forKey:(NSString *)kCTKernAttributeName];
- NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
- paragraphStyle.alignment = label.textAlignment;
- paragraphStyle.lineSpacing = label.lineSpacing;
- paragraphStyle.minimumLineHeight = label.minimumLineHeight > 0 ? label.minimumLineHeight : label.font.lineHeight * label.lineHeightMultiple;
- paragraphStyle.maximumLineHeight = label.maximumLineHeight > 0 ? label.maximumLineHeight : label.font.lineHeight * label.lineHeightMultiple;
- paragraphStyle.lineHeightMultiple = label.lineHeightMultiple;
- paragraphStyle.firstLineHeadIndent = label.firstLineIndent;
- if (label.numberOfLines == 1) {
- paragraphStyle.lineBreakMode = label.lineBreakMode;
- } else {
- paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
- }
- [mutableAttributes setObject:paragraphStyle forKey:(NSString *)kCTParagraphStyleAttributeName];
- } else {
- CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)label.font.fontName, label.font.pointSize, NULL);
- [mutableAttributes setObject:(__bridge id)font forKey:(NSString *)kCTFontAttributeName];
- CFRelease(font);
- [mutableAttributes setObject:(id)[label.textColor CGColor] forKey:(NSString *)kCTForegroundColorAttributeName];
- [mutableAttributes setObject:@(label.kern) forKey:(NSString *)kCTKernAttributeName];
- CTTextAlignment alignment = CTTextAlignmentFromTTTTextAlignment(label.textAlignment);
- CGFloat lineSpacing = label.lineSpacing;
- CGFloat minimumLineHeight = label.minimumLineHeight * label.lineHeightMultiple;
- CGFloat maximumLineHeight = label.maximumLineHeight * label.lineHeightMultiple;
- CGFloat lineSpacingAdjustment = CGFloat_ceil(label.font.lineHeight - label.font.ascender + label.font.descender);
- CGFloat lineHeightMultiple = label.lineHeightMultiple;
- CGFloat firstLineIndent = label.firstLineIndent;
- CTLineBreakMode lineBreakMode = kCTLineBreakByWordWrapping;
- if (label.numberOfLines == 1) {
- lineBreakMode = CTLineBreakModeFromTTTLineBreakMode(label.lineBreakMode);
- }
- CTParagraphStyleSetting paragraphStyles[12] = {
- {.spec = kCTParagraphStyleSpecifierAlignment, .valueSize = sizeof(CTTextAlignment), .value = (const void *)&alignment},
- {.spec = kCTParagraphStyleSpecifierLineBreakMode, .valueSize = sizeof(CTLineBreakMode), .value = (const void *)&lineBreakMode},
- {.spec = kCTParagraphStyleSpecifierLineSpacing, .valueSize = sizeof(CGFloat), .value = (const void *)&lineSpacing},
- {.spec = kCTParagraphStyleSpecifierMinimumLineSpacing, .valueSize = sizeof(CGFloat), .value = (const void *)&minimumLineHeight},
- {.spec = kCTParagraphStyleSpecifierMaximumLineSpacing, .valueSize = sizeof(CGFloat), .value = (const void *)&maximumLineHeight},
- {.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment, .valueSize = sizeof (CGFloat), .value = (const void *)&lineSpacingAdjustment},
- {.spec = kCTParagraphStyleSpecifierLineHeightMultiple, .valueSize = sizeof(CGFloat), .value = (const void *)&lineHeightMultiple},
- {.spec = kCTParagraphStyleSpecifierFirstLineHeadIndent, .valueSize = sizeof(CGFloat), .value = (const void *)&firstLineIndent},
- };
- CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(paragraphStyles, 12);
- [mutableAttributes setObject:(__bridge id)paragraphStyle forKey:(NSString *)kCTParagraphStyleAttributeName];
- CFRelease(paragraphStyle);
- }
- return [NSDictionary dictionaryWithDictionary:mutableAttributes];
- }
- static inline NSAttributedString * NSAttributedStringByScalingFontSize(NSAttributedString *attributedString, CGFloat scale) {
- NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy];
- [mutableAttributedString enumerateAttribute:(NSString *)kCTFontAttributeName inRange:NSMakeRange(0, [mutableAttributedString length]) options:0 usingBlock:^(id value, NSRange range, BOOL * __unused stop) {
- UIFont *font = (UIFont *)value;
- if (font) {
- NSString *fontName;
- CGFloat pointSize;
- if ([font isKindOfClass:[UIFont class]]) {
- fontName = font.fontName;
- pointSize = font.pointSize;
- } else {
- fontName = (NSString *)CFBridgingRelease(CTFontCopyName((__bridge CTFontRef)font, kCTFontPostScriptNameKey));
- pointSize = CTFontGetSize((__bridge CTFontRef)font);
- }
- [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName range:range];
- CTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef)fontName, CGFloat_floor(pointSize * scale), NULL);
- [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)fontRef range:range];
- CFRelease(fontRef);
- }
- }];
- return mutableAttributedString;
- }
- static inline NSAttributedString * NSAttributedStringBySettingColorFromContext(NSAttributedString *attributedString, UIColor *color) {
- if (!color) {
- return attributedString;
- }
- NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy];
- [mutableAttributedString enumerateAttribute:(NSString *)kCTForegroundColorFromContextAttributeName inRange:NSMakeRange(0, [mutableAttributedString length]) options:0 usingBlock:^(id value, NSRange range, __unused BOOL *stop) {
- BOOL usesColorFromContext = (BOOL)value;
- if (usesColorFromContext) {
- [mutableAttributedString setAttributes:[NSDictionary dictionaryWithObject:color forKey:(NSString *)kCTForegroundColorAttributeName] range:range];
- [mutableAttributedString removeAttribute:(NSString *)kCTForegroundColorFromContextAttributeName range:range];
- }
- }];
- return mutableAttributedString;
- }
- static inline CGSize CTFramesetterSuggestFrameSizeForAttributedStringWithConstraints(CTFramesetterRef framesetter, NSAttributedString *attributedString, CGSize size, NSUInteger numberOfLines) {
- CFRange rangeToSize = CFRangeMake(0, (CFIndex)[attributedString length]);
- CGSize constraints = CGSizeMake(size.width, TTTFLOAT_MAX);
- if (numberOfLines == 1) {
- // If there is one line, the size that fits is the full width of the line
- constraints = CGSizeMake(TTTFLOAT_MAX, TTTFLOAT_MAX);
- } else if (numberOfLines > 0) {
- // If the line count of the label more than 1, limit the range to size to the number of lines that have been set
- CGMutablePathRef path = CGPathCreateMutable();
- CGPathAddRect(path, NULL, CGRectMake(0.0f, 0.0f, constraints.width, TTTFLOAT_MAX));
- CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
- CFArrayRef lines = CTFrameGetLines(frame);
- if (CFArrayGetCount(lines) > 0) {
- NSInteger lastVisibleLineIndex = MIN((CFIndex)numberOfLines, CFArrayGetCount(lines)) - 1;
- CTLineRef lastVisibleLine = CFArrayGetValueAtIndex(lines, lastVisibleLineIndex);
- CFRange rangeToLayout = CTLineGetStringRange(lastVisibleLine);
- rangeToSize = CFRangeMake(0, rangeToLayout.location + rangeToLayout.length);
- }
- CFRelease(frame);
- CFRelease(path);
- }
- CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, rangeToSize, NULL, constraints, NULL);
- return CGSizeMake(CGFloat_ceil(suggestedSize.width), CGFloat_ceil(suggestedSize.height));
- }
- @interface TTTAttributedLabel ()
- @property (readwrite, nonatomic, copy) NSAttributedString *inactiveAttributedText;
- @property (readwrite, nonatomic, copy) NSAttributedString *renderedAttributedText;
- @property (readwrite, atomic, strong) NSDataDetector *dataDetector;
- @property (readwrite, nonatomic, strong) NSArray *linkModels;
- @property (readwrite, nonatomic, strong) TTTAttributedLabelLink *activeLink;
- @property (readwrite, nonatomic, strong) NSArray *accessibilityElements;
- - (void) longPressGestureDidFire:(UILongPressGestureRecognizer *)sender;
- @end
- @implementation TTTAttributedLabel {
- @private
- BOOL _needsFramesetter;
- CTFramesetterRef _framesetter;
- CTFramesetterRef _highlightFramesetter;
- }
- @dynamic text;
- @synthesize attributedText = _attributedText;
- #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
- #ifndef kCFCoreFoundationVersionNumber_iOS_7_0
- #define kCFCoreFoundationVersionNumber_iOS_7_0 847.2
- #endif
- + (void)load {
- static dispatch_once_t onceToken;
- dispatch_once(&onceToken, ^{
- if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iOS_7_0) {
- Class class = [self class];
- Class superclass = class_getSuperclass(class);
- NSArray *strings = @[
- NSStringFromSelector(@selector(isAccessibilityElement)),
- NSStringFromSelector(@selector(accessibilityElementCount)),
- NSStringFromSelector(@selector(accessibilityElementAtIndex:)),
- NSStringFromSelector(@selector(indexOfAccessibilityElement:)),
- ];
- for (NSString *string in strings) {
- SEL selector = NSSelectorFromString(string);
- IMP superImplementation = class_getMethodImplementation(superclass, selector);
- Method method = class_getInstanceMethod(class, selector);
- const char *types = method_getTypeEncoding(method);
- class_replaceMethod(class, selector, superImplementation, types);
- }
- }
- });
- }
- #endif
- - (instancetype)initWithFrame:(CGRect)frame {
- self = [super initWithFrame:frame];
- if (!self) {
- return nil;
- }
- [self commonInit];
- return self;
- }
- - (void)commonInit {
- self.userInteractionEnabled = YES;
- self.multipleTouchEnabled = NO;
- self.textInsets = UIEdgeInsetsZero;
- self.lineHeightMultiple = 1.0f;
- self.linkModels = [NSArray array];
- self.linkBackgroundEdgeInset = UIEdgeInsetsMake(0.0f, -1.0f, 0.0f, -1.0f);
- NSMutableDictionary *mutableLinkAttributes = [NSMutableDictionary dictionary];
- [mutableLinkAttributes setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCTUnderlineStyleAttributeName];
- NSMutableDictionary *mutableActiveLinkAttributes = [NSMutableDictionary dictionary];
- [mutableActiveLinkAttributes setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCTUnderlineStyleAttributeName];
- NSMutableDictionary *mutableInactiveLinkAttributes = [NSMutableDictionary dictionary];
- [mutableInactiveLinkAttributes setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCTUnderlineStyleAttributeName];
- if ([NSMutableParagraphStyle class]) {
- [mutableLinkAttributes setObject:[UIColor blueColor] forKey:(NSString *)kCTForegroundColorAttributeName];
- [mutableActiveLinkAttributes setObject:[UIColor redColor] forKey:(NSString *)kCTForegroundColorAttributeName];
- [mutableInactiveLinkAttributes setObject:[UIColor grayColor] forKey:(NSString *)kCTForegroundColorAttributeName];
- } else {
- [mutableLinkAttributes setObject:(__bridge id)[[UIColor blueColor] CGColor] forKey:(NSString *)kCTForegroundColorAttributeName];
- [mutableActiveLinkAttributes setObject:(__bridge id)[[UIColor redColor] CGColor] forKey:(NSString *)kCTForegroundColorAttributeName];
- [mutableInactiveLinkAttributes setObject:(__bridge id)[[UIColor grayColor] CGColor] forKey:(NSString *)kCTForegroundColorAttributeName];
- }
- self.linkAttributes = [NSDictionary dictionaryWithDictionary:mutableLinkAttributes];
- self.activeLinkAttributes = [NSDictionary dictionaryWithDictionary:mutableActiveLinkAttributes];
- self.inactiveLinkAttributes = [NSDictionary dictionaryWithDictionary:mutableInactiveLinkAttributes];
- _extendsLinkTouchArea = YES;
- _longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self
- action:@selector(longPressGestureDidFire:)];
- self.longPressGestureRecognizer.delegate = self;
- [self addGestureRecognizer:self.longPressGestureRecognizer];
- }
- - (void)dealloc {
- if (_framesetter) {
- CFRelease(_framesetter);
- }
- if (_highlightFramesetter) {
- CFRelease(_highlightFramesetter);
- }
-
- if (_longPressGestureRecognizer) {
- [self removeGestureRecognizer:_longPressGestureRecognizer];
- }
- }
- #pragma mark -
- + (CGSize)sizeThatFitsAttributedString:(NSAttributedString *)attributedString
- withConstraints:(CGSize)size
- limitedToNumberOfLines:(NSUInteger)numberOfLines
- {
- if (!attributedString || attributedString.length == 0) {
- return CGSizeZero;
- }
- CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attributedString);
- CGSize calculatedSize = CTFramesetterSuggestFrameSizeForAttributedStringWithConstraints(framesetter, attributedString, size, numberOfLines);
- CFRelease(framesetter);
- return calculatedSize;
- }
- #pragma mark -
- - (void)setAttributedText:(NSAttributedString *)text {
- if ([text isEqualToAttributedString:_attributedText]) {
- return;
- }
- _attributedText = [text copy];
- [self setNeedsFramesetter];
- [self setNeedsDisplay];
- #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 60000
- if ([self respondsToSelector:@selector(invalidateIntrinsicContentSize)]) {
- [self invalidateIntrinsicContentSize];
- }
- #endif
- [super setText:[self.attributedText string]];
- }
- - (NSAttributedString *)renderedAttributedText {
- if (!_renderedAttributedText) {
- self.renderedAttributedText = NSAttributedStringBySettingColorFromContext(self.attributedText, self.textColor);
- }
- return _renderedAttributedText;
- }
- - (NSArray *) links {
- return [_linkModels valueForKey:@"result"];
- }
- - (void)setLinkModels:(NSArray *)linkModels {
- _linkModels = linkModels;
-
- self.accessibilityElements = nil;
- }
- - (void)setNeedsFramesetter {
- // Reset the rendered attributed text so it has a chance to regenerate
- self.renderedAttributedText = nil;
- _needsFramesetter = YES;
- }
- - (CTFramesetterRef)framesetter {
- if (_needsFramesetter) {
- @synchronized(self) {
- CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)self.renderedAttributedText);
- [self setFramesetter:framesetter];
- [self setHighlightFramesetter:nil];
- _needsFramesetter = NO;
- if (framesetter) {
- CFRelease(framesetter);
- }
- }
- }
- return _framesetter;
- }
- - (void)setFramesetter:(CTFramesetterRef)framesetter {
- if (framesetter) {
- CFRetain(framesetter);
- }
- if (_framesetter) {
- CFRelease(_framesetter);
- }
- _framesetter = framesetter;
- }
- - (CTFramesetterRef)highlightFramesetter {
- return _highlightFramesetter;
- }
- - (void)setHighlightFramesetter:(CTFramesetterRef)highlightFramesetter {
- if (highlightFramesetter) {
- CFRetain(highlightFramesetter);
- }
- if (_highlightFramesetter) {
- CFRelease(_highlightFramesetter);
- }
- _highlightFramesetter = highlightFramesetter;
- }
- - (CGFloat)leading {
- return self.lineSpacing;
- }
- - (void)setLeading:(CGFloat)leading {
- self.lineSpacing = leading;
- }
- #pragma mark -
- - (NSTextCheckingTypes)dataDetectorTypes {
- return self.enabledTextCheckingTypes;
- }
- - (void)setDataDetectorTypes:(NSTextCheckingTypes)dataDetectorTypes {
- self.enabledTextCheckingTypes = dataDetectorTypes;
- }
- - (void)setEnabledTextCheckingTypes:(NSTextCheckingTypes)enabledTextCheckingTypes {
- if (self.enabledTextCheckingTypes == enabledTextCheckingTypes) {
- return;
- }
-
- _enabledTextCheckingTypes = enabledTextCheckingTypes;
- if (self.enabledTextCheckingTypes) {
- self.dataDetector = [NSDataDetector dataDetectorWithTypes:self.enabledTextCheckingTypes error:nil];
- } else {
- self.dataDetector = nil;
- }
- }
- - (void)addLink:(TTTAttributedLabelLink *)link {
- [self addLinks:@[link]];
- }
- - (void)addLinks:(NSArray *)links {
- NSMutableArray *mutableLinkModels = [NSMutableArray arrayWithArray:self.linkModels];
-
- NSMutableAttributedString *mutableAttributedString = [self.attributedText mutableCopy];
- for (TTTAttributedLabelLink *link in links) {
- if (link.attributes) {
- [mutableAttributedString addAttributes:link.attributes range:link.result.range];
- }
- }
- self.attributedText = mutableAttributedString;
- [self setNeedsDisplay];
- [mutableLinkModels addObjectsFromArray:links];
-
- self.linkModels = [NSArray arrayWithArray:mutableLinkModels];
- }
- - (TTTAttributedLabelLink *)addLinkWithTextCheckingResult:(NSTextCheckingResult *)result
- attributes:(NSDictionary *)attributes
- {
- return [self addLinksWithTextCheckingResults:@[result] attributes:attributes].firstObject;
- }
- - (NSArray *)addLinksWithTextCheckingResults:(NSArray *)results
- attributes:(NSDictionary *)attributes
- {
- NSMutableArray *links = [NSMutableArray array];
-
- for (NSTextCheckingResult *result in results) {
- NSDictionary *activeAttributes = attributes ? self.activeLinkAttributes : nil;
- NSDictionary *inactiveAttributes = attributes ? self.inactiveLinkAttributes : nil;
-
- TTTAttributedLabelLink *link = [[TTTAttributedLabelLink alloc] initWithAttributes:attributes
- activeAttributes:activeAttributes
- inactiveAttributes:inactiveAttributes
- textCheckingResult:result];
-
- [links addObject:link];
- }
-
- [self addLinks:links];
-
- return links;
- }
- - (TTTAttributedLabelLink *)addLinkWithTextCheckingResult:(NSTextCheckingResult *)result {
- return [self addLinkWithTextCheckingResult:result attributes:self.linkAttributes];
- }
- - (TTTAttributedLabelLink *)addLinkToURL:(NSURL *)url
- withRange:(NSRange)range
- {
- return [self addLinkWithTextCheckingResult:[NSTextCheckingResult linkCheckingResultWithRange:range URL:url]];
- }
- - (TTTAttributedLabelLink *)addLinkToAddress:(NSDictionary *)addressComponents
- withRange:(NSRange)range
- {
- return [self addLinkWithTextCheckingResult:[NSTextCheckingResult addressCheckingResultWithRange:range components:addressComponents]];
- }
- - (TTTAttributedLabelLink *)addLinkToPhoneNumber:(NSString *)phoneNumber
- withRange:(NSRange)range
- {
- return [self addLinkWithTextCheckingResult:[NSTextCheckingResult phoneNumberCheckingResultWithRange:range phoneNumber:phoneNumber]];
- }
- - (TTTAttributedLabelLink *)addLinkToDate:(NSDate *)date
- withRange:(NSRange)range
- {
- return [self addLinkWithTextCheckingResult:[NSTextCheckingResult dateCheckingResultWithRange:range date:date]];
- }
- - (TTTAttributedLabelLink *)addLinkToDate:(NSDate *)date
- timeZone:(NSTimeZone *)timeZone
- duration:(NSTimeInterval)duration
- withRange:(NSRange)range
- {
- return [self addLinkWithTextCheckingResult:[NSTextCheckingResult dateCheckingResultWithRange:range date:date timeZone:timeZone duration:duration]];
- }
- - (TTTAttributedLabelLink *)addLinkToTransitInformation:(NSDictionary *)components
- withRange:(NSRange)range
- {
- return [self addLinkWithTextCheckingResult:[NSTextCheckingResult transitInformationCheckingResultWithRange:range components:components]];
- }
- #pragma mark -
- - (BOOL)containslinkAtPoint:(CGPoint)point {
- return [self linkAtPoint:point] != nil;
- }
- - (TTTAttributedLabelLink *)linkAtPoint:(CGPoint)point {
-
- // Stop quickly if none of the points to be tested are in the bounds.
- if (!CGRectContainsPoint(CGRectInset(self.bounds, -15.f, -15.f), point) || self.links.count == 0) {
- return nil;
- }
-
- TTTAttributedLabelLink *result = [self linkAtCharacterIndex:[self characterIndexAtPoint:point]];
-
- if (!result && self.extendsLinkTouchArea) {
- result = [self linkAtRadius:2.5f aroundPoint:point]
- ?: [self linkAtRadius:5.f aroundPoint:point]
- ?: [self linkAtRadius:7.5f aroundPoint:point]
- ?: [self linkAtRadius:12.5f aroundPoint:point]
- ?: [self linkAtRadius:15.f aroundPoint:point];
- }
-
- return result;
- }
- - (TTTAttributedLabelLink *)linkAtRadius:(const CGFloat)radius aroundPoint:(CGPoint)point {
- const CGFloat diagonal = CGFloat_sqrt(2 * radius * radius);
- const CGPoint deltas[] = {
- CGPointMake(0, -radius), CGPointMake(0, radius), // Above and below
- CGPointMake(-radius, 0), CGPointMake(radius, 0), // Beside
- CGPointMake(-diagonal, -diagonal), CGPointMake(-diagonal, diagonal),
- CGPointMake(diagonal, diagonal), CGPointMake(diagonal, -diagonal) // Diagonal
- };
- const size_t count = sizeof(deltas) / sizeof(CGPoint);
-
- TTTAttributedLabelLink *link = nil;
-
- for (NSInteger i = 0; i < count && link.result == nil; i ++) {
- CGPoint currentPoint = CGPointMake(point.x + deltas[i].x, point.y + deltas[i].y);
- link = [self linkAtCharacterIndex:[self characterIndexAtPoint:currentPoint]];
- }
-
- return link;
- }
- - (TTTAttributedLabelLink *)linkAtCharacterIndex:(CFIndex)idx {
- // Do not enumerate if the index is outside of the bounds of the text.
- if (!NSLocationInRange((NSUInteger)idx, NSMakeRange(0, self.attributedText.length))) {
- return nil;
- }
-
- NSEnumerator *enumerator = [self.linkModels reverseObjectEnumerator];
- TTTAttributedLabelLink *link = nil;
- while ((link = [enumerator nextObject])) {
- if (NSLocationInRange((NSUInteger)idx, link.result.range)) {
- return link;
- }
- }
- return nil;
- }
- - (CFIndex)characterIndexAtPoint:(CGPoint)p {
- if (!CGRectContainsPoint(self.bounds, p)) {
- return NSNotFound;
- }
- CGRect textRect = [self textRectForBounds:self.bounds limitedToNumberOfLines:self.numberOfLines];
- if (!CGRectContainsPoint(textRect, p)) {
- return NSNotFound;
- }
- // Offset tap coordinates by textRect origin to make them relative to the origin of frame
- p = CGPointMake(p.x - textRect.origin.x, p.y - textRect.origin.y);
- // Convert tap coordinates (start at top left) to CT coordinates (start at bottom left)
- p = CGPointMake(p.x, textRect.size.height - p.y);
- CGMutablePathRef path = CGPathCreateMutable();
- CGPathAddRect(path, NULL, textRect);
- CTFrameRef frame = CTFramesetterCreateFrame([self framesetter], CFRangeMake(0, (CFIndex)[self.attributedText length]), path, NULL);
- if (frame == NULL) {
- CFRelease(path);
- return NSNotFound;
- }
- CFArrayRef lines = CTFrameGetLines(frame);
- NSInteger numberOfLines = self.numberOfLines > 0 ? MIN(self.numberOfLines, CFArrayGetCount(lines)) : CFArrayGetCount(lines);
- if (numberOfLines == 0) {
- CFRelease(frame);
- CFRelease(path);
- return NSNotFound;
- }
- CFIndex idx = NSNotFound;
- CGPoint lineOrigins[numberOfLines];
- CTFrameGetLineOrigins(frame, CFRangeMake(0, numberOfLines), lineOrigins);
- for (CFIndex lineIndex = 0; lineIndex < numberOfLines; lineIndex++) {
- CGPoint lineOrigin = lineOrigins[lineIndex];
- CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex);
- // Get bounding information of line
- CGFloat ascent = 0.0f, descent = 0.0f, leading = 0.0f;
- CGFloat width = (CGFloat)CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
- CGFloat yMin = (CGFloat)floor(lineOrigin.y - descent);
- CGFloat yMax = (CGFloat)ceil(lineOrigin.y + ascent);
- // Apply penOffset using flushFactor for horizontal alignment to set lineOrigin since this is the horizontal offset from drawFramesetter
- CGFloat flushFactor = TTTFlushFactorForTextAlignment(self.textAlignment);
- CGFloat penOffset = (CGFloat)CTLineGetPenOffsetForFlush(line, flushFactor, textRect.size.width);
- lineOrigin.x = penOffset;
- // Check if we've already passed the line
- if (p.y > yMax) {
- break;
- }
- // Check if the point is within this line vertically
- if (p.y >= yMin) {
- // Check if the point is within this line horizontally
- if (p.x >= lineOrigin.x && p.x <= lineOrigin.x + width) {
- // Convert CT coordinates to line-relative coordinates
- CGPoint relativePoint = CGPointMake(p.x - lineOrigin.x, p.y - lineOrigin.y);
- idx = CTLineGetStringIndexForPosition(line, relativePoint);
- break;
- }
- }
- }
- CFRelease(frame);
- CFRelease(path);
- return idx;
- }
- #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
- - (CGRect)boundingRectForCharacterRange:(NSRange)range {
- NSMutableAttributedString *mutableAttributedString = [self.attributedText mutableCopy];
- NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:mutableAttributedString];
- NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
- [textStorage addLayoutManager:layoutManager];
- NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:self.bounds.size];
- [layoutManager addTextContainer:textContainer];
- NSRange glyphRange;
- [layoutManager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange];
- return [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer];
- }
- #endif
- - (void)drawFramesetter:(CTFramesetterRef)framesetter
- attributedString:(NSAttributedString *)attributedString
- textRange:(CFRange)textRange
- inRect:(CGRect)rect
- context:(CGContextRef)c
- {
- CGMutablePathRef path = CGPathCreateMutable();
- CGPathAddRect(path, NULL, rect);
- CTFrameRef frame = CTFramesetterCreateFrame(framesetter, textRange, path, NULL);
- [self drawBackground:frame inRect:rect context:c];
- CFArrayRef lines = CTFrameGetLines(frame);
- NSInteger numberOfLines = self.numberOfLines > 0 ? MIN(self.numberOfLines, CFArrayGetCount(lines)) : CFArrayGetCount(lines);
- BOOL truncateLastLine = (self.lineBreakMode == TTTLineBreakByTruncatingHead || self.lineBreakMode == TTTLineBreakByTruncatingMiddle || self.lineBreakMode == TTTLineBreakByTruncatingTail);
- CGPoint lineOrigins[numberOfLines];
- CTFrameGetLineOrigins(frame, CFRangeMake(0, numberOfLines), lineOrigins);
- for (CFIndex lineIndex = 0; lineIndex < numberOfLines; lineIndex++) {
- CGPoint lineOrigin = lineOrigins[lineIndex];
- CGContextSetTextPosition(c, lineOrigin.x, lineOrigin.y);
- CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex);
- CGFloat descent = 0.0f;
- CTLineGetTypographicBounds((CTLineRef)line, NULL, &descent, NULL);
- // Adjust pen offset for flush depending on text alignment
- CGFloat flushFactor = TTTFlushFactorForTextAlignment(self.textAlignment);
- if (lineIndex == numberOfLines - 1 && truncateLastLine) {
- // Check if the range of text in the last line reaches the end of the full attributed string
- CFRange lastLineRange = CTLineGetStringRange(line);
- if (!(lastLineRange.length == 0 && lastLineRange.location == 0) && lastLineRange.location + lastLineRange.length < textRange.location + textRange.length) {
- // Get correct truncationType and attribute position
- CTLineTruncationType truncationType;
- CFIndex truncationAttributePosition = lastLineRange.location;
- TTTLineBreakMode lineBreakMode = self.lineBreakMode;
- // Multiple lines, only use UILineBreakModeTailTruncation
- if (numberOfLines != 1) {
- lineBreakMode = TTTLineBreakByTruncatingTail;
- }
- switch (lineBreakMode) {
- case TTTLineBreakByTruncatingHead:
- truncationType = kCTLineTruncationStart;
- break;
- case TTTLineBreakByTruncatingMiddle:
- truncationType = kCTLineTruncationMiddle;
- truncationAttributePosition += (lastLineRange.length / 2);
- break;
- case TTTLineBreakByTruncatingTail:
- default:
- truncationType = kCTLineTruncationEnd;
- truncationAttributePosition += (lastLineRange.length - 1);
- break;
- }
- #pragma clang diagnostic push
- #pragma clang diagnostic ignored "-Wdeprecated-declarations"
- NSAttributedString *attributedTruncationString = self.attributedTruncationToken;
- if (!attributedTruncationString) {
- NSString *truncationTokenString = self.truncationTokenString;
- if (!truncationTokenString) {
- truncationTokenString = @"\u2026"; // Unicode Character 'HORIZONTAL ELLIPSIS' (U+2026)
- }
-
- NSDictionary *truncationTokenStringAttributes = self.truncationTokenStringAttributes;
- if (!truncationTokenStringAttributes) {
- truncationTokenStringAttributes = [attributedString attributesAtIndex:(NSUInteger)truncationAttributePosition effectiveRange:NULL];
- }
-
- attributedTruncationString = [[NSAttributedString alloc] initWithString:truncationTokenString attributes:truncationTokenStringAttributes];
- }
- CTLineRef truncationToken = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)attributedTruncationString);
- #pragma clang diagnostic pop
- // Append truncationToken to the string
- // because if string isn't too long, CT won't add the truncationToken on its own.
- // There is no chance of a double truncationToken because CT only adds the
- // token if it removes characters (and the one we add will go first)
- NSMutableAttributedString *truncationString = [[NSMutableAttributedString alloc] initWithAttributedString:
- [attributedString attributedSubstringFromRange:
- NSMakeRange((NSUInteger)lastLineRange.location,
- (NSUInteger)lastLineRange.length)]];
- if (lastLineRange.length > 0) {
- // 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.
- unichar lastCharacter = [[truncationString string] characterAtIndex:(NSUInteger)(lastLineRange.length - 1)];
- if ([[NSCharacterSet newlineCharacterSet] characterIsMember:lastCharacter]) {
- [truncationString deleteCharactersInRange:NSMakeRange((NSUInteger)(lastLineRange.length - 1), 1)];
- }
- }
- [truncationString appendAttributedString:attributedTruncationString];
- CTLineRef truncationLine = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)truncationString);
- // Truncate the line in case it is too long.
- CTLineRef truncatedLine = CTLineCreateTruncatedLine(truncationLine, rect.size.width, truncationType, truncationToken);
- if (!truncatedLine) {
- // If the line is not as wide as the truncationToken, truncatedLine is NULL
- truncatedLine = CFRetain(truncationToken);
- }
- CGFloat penOffset = (CGFloat)CTLineGetPenOffsetForFlush(truncatedLine, flushFactor, rect.size.width);
- CGContextSetTextPosition(c, penOffset, lineOrigin.y - descent - self.font.descender);
- CTLineDraw(truncatedLine, c);
-
- NSRange linkRange;
- if ([attributedTruncationString attribute:NSLinkAttributeName atIndex:0 effectiveRange:&linkRange]) {
- NSRange tokenRange = [truncationString.string rangeOfString:attributedTruncationString.string];
- NSRange tokenLinkRange = NSMakeRange((NSUInteger)(lastLineRange.location+lastLineRange.length)-tokenRange.length, (NSUInteger)tokenRange.length);
-
- [self addLinkToURL:[attributedTruncationString attribute:NSLinkAttributeName atIndex:0 effectiveRange:&linkRange] withRange:tokenLinkRange];
- }
- CFRelease(truncatedLine);
- CFRelease(truncationLine);
- CFRelease(truncationToken);
- } else {
- CGFloat penOffset = (CGFloat)CTLineGetPenOffsetForFlush(line, flushFactor, rect.size.width);
- CGContextSetTextPosition(c, penOffset, lineOrigin.y - descent - self.font.descender);
- CTLineDraw(line, c);
- }
- } else {
- CGFloat penOffset = (CGFloat)CTLineGetPenOffsetForFlush(line, flushFactor, rect.size.width);
- CGContextSetTextPosition(c, penOffset, lineOrigin.y - descent - self.font.descender);
- CTLineDraw(line, c);
- }
- }
- [self drawStrike:frame inRect:rect context:c];
- CFRelease(frame);
- CFRelease(path);
- }
- - (void)drawBackground:(CTFrameRef)frame
- inRect:(CGRect)rect
- context:(CGContextRef)c
- {
- NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
- CGPoint origins[[lines count]];
- CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), origins);
- CFIndex lineIndex = 0;
- for (id line in lines) {
- CGFloat ascent = 0.0f, descent = 0.0f, leading = 0.0f;
- CGFloat width = (CGFloat)CTLineGetTypographicBounds((__bridge CTLineRef)line, &ascent, &descent, &leading) ;
- for (id glyphRun in (__bridge NSArray *)CTLineGetGlyphRuns((__bridge CTLineRef)line)) {
- NSDictionary *attributes = (__bridge NSDictionary *)CTRunGetAttributes((__bridge CTRunRef) glyphRun);
- CGColorRef strokeColor = (__bridge CGColorRef)[attributes objectForKey:kTTTBackgroundStrokeColorAttributeName];
- CGColorRef fillColor = (__bridge CGColorRef)[attributes objectForKey:kTTTBackgroundFillColorAttributeName];
- UIEdgeInsets fillPadding = [[attributes objectForKey:kTTTBackgroundFillPaddingAttributeName] UIEdgeInsetsValue];
- CGFloat cornerRadius = [[attributes objectForKey:kTTTBackgroundCornerRadiusAttributeName] floatValue];
- CGFloat lineWidth = [[attributes objectForKey:kTTTBackgroundLineWidthAttributeName] floatValue];
- if (strokeColor || fillColor) {
- CGRect runBounds = CGRectZero;
- CGFloat runAscent = 0.0f;
- CGFloat runDescent = 0.0f;
- runBounds.size.width = (CGFloat)CTRunGetTypographicBounds((__bridge CTRunRef)glyphRun, CFRangeMake(0, 0), &runAscent, &runDescent, NULL) + fillPadding.left + fillPadding.right;
- runBounds.size.height = runAscent + runDescent + fillPadding.top + fillPadding.bottom;
- CGFloat xOffset = 0.0f;
- CFRange glyphRange = CTRunGetStringRange((__bridge CTRunRef)glyphRun);
- switch (CTRunGetStatus((__bridge CTRunRef)glyphRun)) {
- case kCTRunStatusRightToLeft:
- xOffset = CTLineGetOffsetForStringIndex((__bridge CTLineRef)line, glyphRange.location + glyphRange.length, NULL);
- break;
- default:
- xOffset = CTLineGetOffsetForStringIndex((__bridge CTLineRef)line, glyphRange.location, NULL);
- break;
- }
- runBounds.origin.x = origins[lineIndex].x + rect.origin.x + xOffset - fillPadding.left - rect.origin.x;
- runBounds.origin.y = origins[lineIndex].y + rect.origin.y - fillPadding.bottom - rect.origin.y;
- runBounds.origin.y -= runDescent;
- // Don't draw higlightedLinkBackground too far to the right
- if (CGRectGetWidth(runBounds) > width) {
- runBounds.size.width = width;
- }
- CGPathRef path = [[UIBezierPath bezierPathWithRoundedRect:CGRectInset(UIEdgeInsetsInsetRect(runBounds, self.linkBackgroundEdgeInset), lineWidth, lineWidth) cornerRadius:cornerRadius] CGPath];
- CGContextSetLineJoin(c, kCGLineJoinRound);
- if (fillColor) {
- CGContextSetFillColorWithColor(c, fillColor);
- CGContextAddPath(c, path);
- CGContextFillPath(c);
- }
- if (strokeColor) {
- CGContextSetStrokeColorWithColor(c, strokeColor);
- CGContextAddPath(c, path);
- CGContextStrokePath(c);
- }
- }
- }
- lineIndex++;
- }
- }
- - (void)drawStrike:(CTFrameRef)frame
- inRect:(__unused CGRect)rect
- context:(CGContextRef)c
- {
- NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
- CGPoint origins[[lines count]];
- CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), origins);
- CFIndex lineIndex = 0;
- for (id line in lines) {
- CGFloat ascent = 0.0f, descent = 0.0f, leading = 0.0f;
- CGFloat width = (CGFloat)CTLineGetTypographicBounds((__bridge CTLineRef)line, &ascent, &descent, &leading) ;
- for (id glyphRun in (__bridge NSArray *)CTLineGetGlyphRuns((__bridge CTLineRef)line)) {
- NSDictionary *attributes = (__bridge NSDictionary *)CTRunGetAttributes((__bridge CTRunRef) glyphRun);
- BOOL strikeOut = [[attributes objectForKey:kTTTStrikeOutAttributeName] boolValue];
- NSInteger superscriptStyle = [[attributes objectForKey:(id)kCTSuperscriptAttributeName] integerValue];
- if (strikeOut) {
- CGRect runBounds = CGRectZero;
- CGFloat runAscent = 0.0f;
- CGFloat runDescent = 0.0f;
- runBounds.size.width = (CGFloat)CTRunGetTypographicBounds((__bridge CTRunRef)glyphRun, CFRangeMake(0, 0), &runAscent, &runDescent, NULL);
- runBounds.size.height = runAscent + runDescent;
- CGFloat xOffset = 0.0f;
- CFRange glyphRange = CTRunGetStringRange((__bridge CTRunRef)glyphRun);
- switch (CTRunGetStatus((__bridge CTRunRef)glyphRun)) {
- case kCTRunStatusRightToLeft:
- xOffset = CTLineGetOffsetForStringIndex((__bridge CTLineRef)line, glyphRange.location + glyphRange.length, NULL);
- break;
- default:
- xOffset = CTLineGetOffsetForStringIndex((__bridge CTLineRef)line, glyphRange.location, NULL);
- break;
- }
- runBounds.origin.x = origins[lineIndex].x + xOffset;
- runBounds.origin.y = origins[lineIndex].y;
- runBounds.origin.y -= runDescent;
- // Don't draw strikeout too far to the right
- if (CGRectGetWidth(runBounds) > width) {
- runBounds.size.width = width;
- }
- switch (superscriptStyle) {
- case 1:
- runBounds.origin.y -= runAscent * 0.47f;
- break;
- case -1:
- runBounds.origin.y += runAscent * 0.25f;
- break;
- default:
- break;
- }
- // Use text color, or default to black
- id color = [attributes objectForKey:(id)kCTForegroundColorAttributeName];
- if (color) {
- if ([color isKindOfClass:[UIColor class]]) {
- CGContextSetStrokeColorWithColor(c, [color CGColor]);
- } else {
- CGContextSetStrokeColorWithColor(c, (__bridge CGColorRef)color);
- }
- } else {
- CGContextSetGrayStrokeColor(c, 0.0f, 1.0);
- }
- CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)self.font.fontName, self.font.pointSize, NULL);
- CGContextSetLineWidth(c, CTFontGetUnderlineThickness(font));
- CFRelease(font);
- CGFloat y = CGFloat_round(runBounds.origin.y + runBounds.size.height / 2.0f);
- CGContextMoveToPoint(c, runBounds.origin.x, y);
- CGContextAddLineToPoint(c, runBounds.origin.x + runBounds.size.width, y);
- CGContextStrokePath(c);
- }
- }
- lineIndex++;
- }
- }
- #pragma mark - TTTAttributedLabel
- - (void)setText:(id)text {
- NSParameterAssert(!text || [text isKindOfClass:[NSAttributedString class]] || [text isKindOfClass:[NSString class]]);
- if ([text isKindOfClass:[NSString class]]) {
- [self setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:nil];
- return;
- }
- self.attributedText = text;
- self.activeLink = nil;
- self.linkModels = [NSArray array];
- if (self.attributedText && self.enabledTextCheckingTypes) {
- #if __IPHONE_OS_VERSION_MIN_REQUIRED < 50000
- __unsafe_unretained __typeof(self)weakSelf = self;
- #else
- __weak __typeof(self)weakSelf = self;
- #endif
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- __strong __typeof(weakSelf)strongSelf = weakSelf;
- NSDataDetector *dataDetector = strongSelf.dataDetector;
- if (dataDetector && [dataDetector respondsToSelector:@selector(matchesInString:options:range:)]) {
- NSArray *results = [dataDetector matchesInString:[(NSAttributedString *)text string] options:0 range:NSMakeRange(0, [(NSAttributedString *)text length])];
- if ([results count] > 0) {
- dispatch_sync(dispatch_get_main_queue(), ^{
- if ([[strongSelf.attributedText string] isEqualToString:[(NSAttributedString *)text string]]) {
- [strongSelf addLinksWithTextCheckingResults:results attributes:strongSelf.linkAttributes];
- }
- });
- }
- }
- });
- }
- #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
- if (&NSLinkAttributeName) {
- [self.attributedText enumerateAttribute:NSLinkAttributeName inRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:^(id value, __unused NSRange range, __unused BOOL *stop) {
- if (value) {
- NSURL *URL = [value isKindOfClass:[NSString class]] ? [NSURL URLWithString:value] : value;
- [self addLinkToURL:URL withRange:range];
- }
- }];
- }
- #endif
- }
- - (void)setText:(id)text
- afterInheritingLabelAttributesAndConfiguringWithBlock:(NSMutableAttributedString * (^)(NSMutableAttributedString *mutableAttributedString))block
- {
- NSMutableAttributedString *mutableAttributedString = nil;
- if ([text isKindOfClass:[NSString class]]) {
- mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:text attributes:NSAttributedStringAttributesFromLabel(self)];
- } else {
- mutableAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:text];
- [mutableAttributedString addAttributes:NSAttributedStringAttributesFromLabel(self) range:NSMakeRange(0, [mutableAttributedString length])];
- }
- if (block) {
- mutableAttributedString = block(mutableAttributedString);
- }
- [self setText:mutableAttributedString];
- }
- - (void)setActiveLink:(TTTAttributedLabelLink *)activeLink {
- _activeLink = activeLink;
-
- NSDictionary *activeAttributes = activeLink.activeAttributes ?: self.activeLinkAttributes;
- if (_activeLink && activeAttributes.count > 0) {
- if (!self.inactiveAttributedText) {
- self.inactiveAttributedText = [self.attributedText copy];
- }
- NSMutableAttributedString *mutableAttributedString = [self.inactiveAttributedText mutableCopy];
- if (self.activeLink.result.range.length > 0 && NSLocationInRange(NSMaxRange(self.activeLink.result.range) - 1, NSMakeRange(0, [self.inactiveAttributedText length]))) {
- [mutableAttributedString addAttributes:activeAttributes range:self.activeLink.result.range];
- }
- self.attributedText = mutableAttributedString;
- [self setNeedsDisplay];
- [CATransaction flush];
- } else if (self.inactiveAttributedText) {
- self.attributedText = self.inactiveAttributedText;
- self.inactiveAttributedText = nil;
- [self setNeedsDisplay];
- }
- }
- #pragma mark - UILabel
- - (void)setHighlighted:(BOOL)highlighted {
- [super setHighlighted:highlighted];
- [self setNeedsDisplay];
- }
- // Fixes crash when loading from a UIStoryboard
- - (UIColor *)textColor {
- UIColor *color = [super textColor];
- if (!color) {
- color = [UIColor blackColor];
- }
- return color;
- }
- - (void)setTextColor:(UIColor *)textColor {
- UIColor *oldTextColor = self.textColor;
- [super setTextColor:textColor];
- // Redraw to allow any ColorFromContext attributes a chance to update
- if (textColor != oldTextColor) {
- [self setNeedsFramesetter];
- [self setNeedsDisplay];
- }
- }
- - (CGRect)textRectForBounds:(CGRect)bounds
- limitedToNumberOfLines:(NSInteger)numberOfLines
- {
- bounds = UIEdgeInsetsInsetRect(bounds, self.textInsets);
- if (!self.attributedText) {
- return [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
- }
- CGRect textRect = bounds;
- // 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.
- textRect.size.height = MAX(self.font.lineHeight * MAX(2, numberOfLines), bounds.size.height);
- // Adjust the text to be in the center vertically, if the text size is smaller than bounds
- CGSize textSize = CTFramesetterSuggestFrameSizeWithConstraints([self framesetter], CFRangeMake(0, (CFIndex)[self.attributedText length]), NULL, textRect.size, NULL);
- textSize = CGSizeMake(CGFloat_ceil(textSize.width), CGFloat_ceil(textSize.height)); // Fix for iOS 4, CTFramesetterSuggestFrameSizeWithConstraints sometimes returns fractional sizes
- if (textSize.height < bounds.size.height) {
- CGFloat yOffset = 0.0f;
- switch (self.verticalAlignment) {
- case TTTAttributedLabelVerticalAlignmentCenter:
- yOffset = CGFloat_floor((bounds.size.height - textSize.height) / 2.0f);
- break;
- case TTTAttributedLabelVerticalAlignmentBottom:
- yOffset = bounds.size.height - textSize.height;
- break;
- case TTTAttributedLabelVerticalAlignmentTop:
- default:
- break;
- }
- textRect.origin.y += yOffset;
- }
- return textRect;
- }
- - (void)drawTextInRect:(CGRect)rect {
- CGRect insetRect = UIEdgeInsetsInsetRect(rect, self.textInsets);
- if (!self.attributedText) {
- [super drawTextInRect:insetRect];
- return;
- }
- NSAttributedString *originalAttributedText = nil;
- // Adjust the font size to fit width, if necessarry
- if (self.adjustsFontSizeToFitWidth && self.numberOfLines > 0) {
- // Use infinite width to find the max width, which will be compared to availableWidth if needed.
- CGSize maxSize = (self.numberOfLines > 1) ? CGSizeMake(TTTFLOAT_MAX, TTTFLOAT_MAX) : CGSizeZero;
- CGFloat textWidth = [self sizeThatFits:maxSize].width;
- CGFloat availableWidth = self.frame.size.width * self.numberOfLines;
- if (self.numberOfLines > 1 && self.lineBreakMode == TTTLineBreakByWordWrapping) {
- textWidth *= kTTTLineBreakWordWrapTextWidthScalingFactor;
- }
- if (textWidth > availableWidth && textWidth > 0.0f) {
- originalAttributedText = [self.attributedText copy];
- CGFloat scaleFactor = availableWidth / textWidth;
- if ([self respondsToSelector:@selector(minimumScaleFactor)] && self.minimumScaleFactor > scaleFactor) {
- scaleFactor = self.minimumScaleFactor;
- }
- self.attributedText = NSAttributedStringByScalingFontSize(self.attributedText, scaleFactor);
- }
- }
- CGContextRef c = UIGraphicsGetCurrentContext();
- CGContextSaveGState(c);
- {
- CGContextSetTextMatrix(c, CGAffineTransformIdentity);
- // Inverts the CTM to match iOS coordinates (otherwise text draws upside-down; Mac OS's system is different)
- CGContextTranslateCTM(c, 0.0f, insetRect.size.height);
- CGContextScaleCTM(c, 1.0f, -1.0f);
- CFRange textRange = CFRangeMake(0, (CFIndex)[self.attributedText length]);
- // First, get the text rect (which takes vertical centering into account)
- CGRect textRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
- // CoreText draws its text aligned to the bottom, so we move the CTM here to take our vertical offsets into account
- CGContextTranslateCTM(c, insetRect.origin.x, insetRect.size.height - textRect.origin.y - textRect.size.height);
- // Second, trace the shadow before the actual text, if we have one
- if (self.shadowColor && !self.highlighted) {
- CGContextSetShadowWithColor(c, self.shadowOffset, self.shadowRadius, [self.shadowColor CGColor]);
- } else if (self.highlightedShadowColor) {
- CGContextSetShadowWithColor(c, self.highlightedShadowOffset, self.highlightedShadowRadius, [self.highlightedShadowColor CGColor]);
- }
- // Finally, draw the text or highlighted text itself (on top of the shadow, if there is one)
- if (self.highlightedTextColor && self.highlighted) {
- NSMutableAttributedString *highlightAttributedString = [self.renderedAttributedText mutableCopy];
- [highlightAttributedString addAttribute:(__bridge NSString *)kCTForegroundColorAttributeName value:(id)[self.highlightedTextColor CGColor] range:NSMakeRange(0, highlightAttributedString.length)];
- if (![self highlightFramesetter]) {
- CTFramesetterRef highlightFramesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)highlightAttributedString);
- [self setHighlightFramesetter:highlightFramesetter];
- CFRelease(highlightFramesetter);
- }
- [self drawFramesetter:[self highlightFramesetter] attributedString:highlightAttributedString textRange:textRange inRect:textRect context:c];
- } else {
- [self drawFramesetter:[self framesetter] attributedString:self.renderedAttributedText textRange:textRange inRect:textRect context:c];
- }
- // If we adjusted the font size, set it back to its original size
- if (originalAttributedText) {
- // Use ivar directly to avoid clearing out framesetter and renderedAttributedText
- _attributedText = originalAttributedText;
- }
- }
- CGContextRestoreGState(c);
- }
- #pragma mark - UIAccessibilityElement
- #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
- - (BOOL)isAccessibilityElement {
- return NO;
- }
- - (NSInteger)accessibilityElementCount {
- return (NSInteger)[[self accessibilityElements] count];
- }
- - (id)accessibilityElementAtIndex:(NSInteger)index {
- return [[self accessibilityElements] objectAtIndex:(NSUInteger)index];
- }
- - (NSInteger)indexOfAccessibilityElement:(id)element {
- return (NSInteger)[[self accessibilityElements] indexOfObject:element];
- }
- - (NSArray *)accessibilityElements {
- if (!_accessibilityElements) {
- @synchronized(self) {
- NSMutableArray *mutableAccessibilityItems = [NSMutableArray array];
- for (TTTAttributedLabelLink *link in self.linkModels) {
-
- if (link.result.range.location == NSNotFound) {
- continue;
- }
-
- NSString *sourceText = [self.text isKindOfClass:[NSString class]] ? self.text : [(NSAttributedString *)self.text string];
- NSString *accessibilityLabel = [sourceText substringWithRange:link.result.range];
- NSString *accessibilityValue = link.accessibilityValue;
- if (accessibilityLabel) {
- UIAccessibilityElement *linkElement = [[UIAccessibilityElement alloc] initWithAccessibilityContainer:self];
- linkElement.accessibilityTraits = UIAccessibilityTraitLink;
- linkElement.accessibilityFrame = [self convertRect:[self boundingRectForCharacterRange:link.result.range] toView:self.window];
- linkElement.accessibilityLabel = accessibilityLabel;
- if (![accessibilityLabel isEqualToString:accessibilityValue]) {
- linkElement.accessibilityValue = accessibilityValue;
- }
- [mutableAccessibilityItems addObject:linkElement];
- }
- }
- UIAccessibilityElement *baseElement = [[UIAccessibilityElement alloc] initWithAccessibilityContainer:self];
- baseElement.accessibilityLabel = [super accessibilityLabel];
- baseElement.accessibilityHint = [super accessibilityHint];
- baseElement.accessibilityValue = [super accessibilityValue];
- baseElement.accessibilityFrame = [self convertRect:self.bounds toView:self.window];
- baseElement.accessibilityTraits = [super accessibilityTraits];
- [mutableAccessibilityItems addObject:baseElement];
- self.accessibilityElements = [NSArray arrayWithArray:mutableAccessibilityItems];
- }
- }
- return _accessibilityElements;
- }
- #endif
- #pragma mark - UIView
- - (CGSize)sizeThatFits:(CGSize)size {
- if (!self.attributedText) {
- return [super sizeThatFits:size];
- } else {
- NSMutableAttributedString *fullString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
-
- if (self.attributedTruncationToken) {
- [fullString appendAttributedString:self.attributedTruncationToken];
- }
-
- NSAttributedString *string = [[NSAttributedString alloc] initWithAttributedString:fullString];
-
- CGSize labelSize = CTFramesetterSuggestFrameSizeForAttributedStringWithConstraints([self framesetter], string, size, (NSUInteger)self.numberOfLines);
- labelSize.width += self.textInsets.left + self.textInsets.right;
- labelSize.height += self.textInsets.top + self.textInsets.bottom;
- return labelSize;
- }
- }
- - (CGSize)intrinsicContentSize {
- // There's an implicit width from the original UILabel implementation
- return [self sizeThatFits:[super intrinsicContentSize]];
- }
- #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
- - (void)tintColorDidChange {
- if (!self.inactiveLinkAttributes || [self.inactiveLinkAttributes count] == 0) {
- return;
- }
- BOOL isInactive = (self.tintAdjustmentMode == UIViewTintAdjustmentModeDimmed);
- NSMutableAttributedString *mutableAttributedString = [self.attributedText mutableCopy];
- for (TTTAttributedLabelLink *link in self.linkModels) {
- NSDictionary *attributesToRemove = isInactive ? link.attributes : link.inactiveAttributes;
- NSDictionary *attributesToAdd = isInactive ? link.inactiveAttributes : link.attributes;
-
- [attributesToRemove enumerateKeysAndObjectsUsingBlock:^(NSString *name, __unused id value, __unused BOOL *stop) {
- if (NSMaxRange(link.result.range) <= mutableAttributedString.length) {
- [mutableAttributedString removeAttribute:name range:link.result.range];
- }
- }];
- if (attributesToAdd) {
- if (NSMaxRange(link.result.range) <= mutableAttributedString.length) {
- [mutableAttributedString addAttributes:attributesToAdd range:link.result.range];
- }
- }
- }
- self.attributedText = mutableAttributedString;
- [self setNeedsDisplay];
- }
- #endif
- - (UIView *)hitTest:(CGPoint)point
- withEvent:(UIEvent *)event
- {
- if (![self linkAtPoint:point] || !self.userInteractionEnabled || self.hidden || self.alpha < 0.01) {
- return [super hitTest:point withEvent:event];
- }
- return self;
- }
- #pragma mark - UIResponder
- - (BOOL)canBecomeFirstResponder {
- return YES;
- }
- - (BOOL)canPerformAction:(SEL)action
- withSender:(__unused id)sender
- {
- return (action == @selector(copy:));
- }
- - (void)touchesBegan:(NSSet *)touches
- withEvent:(UIEvent *)event
- {
- UITouch *touch = [touches anyObject];
- self.activeLink = [self linkAtPoint:[touch locationInView:self]];
- if (!self.activeLink) {
- [super touchesBegan:touches withEvent:event];
- }
- }
- - (void)touchesMoved:(NSSet *)touches
- withEvent:(UIEvent *)event
- {
- if (self.activeLink) {
- UITouch *touch = [touches anyObject];
- if (self.activeLink != [self linkAtPoint:[touch locationInView:self]]) {
- self.activeLink = nil;
- }
- } else {
- [super touchesMoved:touches withEvent:event];
- }
- }
- - (void)touchesEnded:(NSSet *)touches
- withEvent:(UIEvent *)event
- {
- if (self.activeLink) {
- if (self.activeLink.linkTapBlock) {
- self.activeLink.linkTapBlock(self, self.activeLink);
- self.activeLink = nil;
- return;
- }
-
- NSTextCheckingResult *result = self.activeLink.result;
- self.activeLink = nil;
- switch (result.resultType) {
- case NSTextCheckingTypeLink:
- if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithURL:)]) {
- [self.delegate attributedLabel:self didSelectLinkWithURL:result.URL];
- return;
- }
- break;
- case NSTextCheckingTypeAddress:
- if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithAddress:)]) {
- [self.delegate attributedLabel:self didSelectLinkWithAddress:result.addressComponents];
- return;
- }
- break;
- case NSTextCheckingTypePhoneNumber:
- if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithPhoneNumber:)]) {
- [self.delegate attributedLabel:self didSelectLinkWithPhoneNumber:result.phoneNumber];
- return;
- }
- break;
- case NSTextCheckingTypeDate:
- if (result.timeZone && [self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithDate:timeZone:duration:)]) {
- [self.delegate attributedLabel:self didSelectLinkWithDate:result.date timeZone:result.timeZone duration:result.duration];
- return;
- } else if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithDate:)]) {
- [self.delegate attributedLabel:self didSelectLinkWithDate:result.date];
- return;
- }
- break;
- case NSTextCheckingTypeTransitInformation:
- if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithTransitInformation:)]) {
- [self.delegate attributedLabel:self didSelectLinkWithTransitInformation:result.components];
- return;
- }
- default:
- break;
- }
- // Fallback to `attributedLabel:didSelectLinkWithTextCheckingResult:` if no other delegate method matched.
- if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithTextCheckingResult:)]) {
- [self.delegate attributedLabel:self didSelectLinkWithTextCheckingResult:result];
- }
- } else {
- [super touchesEnded:touches withEvent:event];
- }
- }
- - (void)touchesCancelled:(NSSet *)touches
- withEvent:(UIEvent *)event
- {
- if (self.activeLink) {
- self.activeLink = nil;
- } else {
- [super touchesCancelled:touches withEvent:event];
- }
- }
- #pragma mark - UIGestureRecognizerDelegate
- - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
- return [self containslinkAtPoint:[touch locationInView:self]];
- }
- #pragma mark - UILongPressGestureRecognizer
- - (void)longPressGestureDidFire:(UILongPressGestureRecognizer *)sender {
- switch (sender.state) {
- case UIGestureRecognizerStateBegan: {
- CGPoint touchPoint = [sender locationInView:self];
- TTTAttributedLabelLink *link = [self linkAtPoint:touchPoint];
-
- if (link) {
- if (link.linkLongPressBlock) {
- link.linkLongPressBlock(self, link);
- return;
- }
-
- NSTextCheckingResult *result = link.result;
-
- if (!result) {
- return;
- }
-
- switch (result.resultType) {
- case NSTextCheckingTypeLink:
- if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithURL:atPoint:)]) {
- [self.delegate attributedLabel:self didLongPressLinkWithURL:result.URL atPoint:touchPoint];
- return;
- }
- break;
- case NSTextCheckingTypeAddress:
- if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithAddress:atPoint:)]) {
- [self.delegate attributedLabel:self didLongPressLinkWithAddress:result.addressComponents atPoint:touchPoint];
- return;
- }
- break;
- case NSTextCheckingTypePhoneNumber:
- if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithPhoneNumber:atPoint:)]) {
- [self.delegate attributedLabel:self didLongPressLinkWithPhoneNumber:result.phoneNumber atPoint:touchPoint];
- return;
- }
- break;
- case NSTextCheckingTypeDate:
- if (result.timeZone && [self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithDate:timeZone:duration:atPoint:)]) {
- [self.delegate attributedLabel:self didLongPressLinkWithDate:result.date timeZone:result.timeZone duration:result.duration atPoint:touchPoint];
- return;
- } else if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithDate:atPoint:)]) {
- [self.delegate attributedLabel:self didLongPressLinkWithDate:result.date atPoint:touchPoint];
- return;
- }
- break;
- case NSTextCheckingTypeTransitInformation:
- if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithTransitInformation:atPoint:)]) {
- [self.delegate attributedLabel:self didLongPressLinkWithTransitInformation:result.components atPoint:touchPoint];
- return;
- }
- default:
- break;
- }
-
- // Fallback to `attributedLabel:didLongPressLinkWithTextCheckingResult:atPoint:` if no other delegate method matched.
- if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithTextCheckingResult:atPoint:)]) {
- [self.delegate attributedLabel:self didLongPressLinkWithTextCheckingResult:result atPoint:touchPoint];
- }
- }
- break;
- }
- default:
- break;
- }
- }
- #pragma mark - UIResponderStandardEditActions
- - (void)copy:(__unused id)sender {
- [[UIPasteboard generalPasteboard] setString:self.text];
- }
- #pragma mark - NSCoding
- - (void)encodeWithCoder:(NSCoder *)coder {
- [super encodeWithCoder:coder];
- [coder encodeObject:@(self.enabledTextCheckingTypes) forKey:NSStringFromSelector(@selector(enabledTextCheckingTypes))];
- [coder encodeObject:self.linkModels forKey:NSStringFromSelector(@selector(linkModels))];
- if ([NSMutableParagraphStyle class]) {
- [coder encodeObject:self.linkAttributes forKey:NSStringFromSelector(@selector(linkAttributes))];
- [coder encodeObject:self.activeLinkAttributes forKey:NSStringFromSelector(@selector(activeLinkAttributes))];
- [coder encodeObject:self.inactiveLinkAttributes forKey:NSStringFromSelector(@selector(inactiveLinkAttributes))];
- }
- [coder encodeObject:@(self.shadowRadius) forKey:NSStringFromSelector(@selector(shadowRadius))];
- [coder encodeObject:@(self.highlightedShadowRadius) forKey:NSStringFromSelector(@selector(highlightedShadowRadius))];
- [coder encodeCGSize:self.highlightedShadowOffset forKey:NSStringFromSelector(@selector(highlightedShadowOffset))];
- [coder encodeObject:self.highlightedShadowColor forKey:NSStringFromSelector(@selector(highlightedShadowColor))];
- [coder encodeObject:@(self.kern) forKey:NSStringFromSelector(@selector(kern))];
- [coder encodeObject:@(self.firstLineIndent) forKey:NSStringFromSelector(@selector(firstLineIndent))];
- [coder encodeObject:@(self.lineSpacing) forKey:NSStringFromSelector(@selector(lineSpacing))];
- [coder encodeObject:@(self.lineHeightMultiple) forKey:NSStringFromSelector(@selector(lineHeightMultiple))];
- [coder encodeUIEdgeInsets:self.textInsets forKey:NSStringFromSelector(@selector(textInsets))];
- [coder encodeInteger:self.verticalAlignment forKey:NSStringFromSelector(@selector(verticalAlignment))];
- #pragma clang diagnostic push
- #pragma clang diagnostic ignored "-Wdeprecated-declarations"
- [coder encodeObject:self.truncationTokenString forKey:NSStringFromSelector(@selector(truncationTokenString))];
- #pragma clang diagnostic pop
- [coder encodeObject:NSStringFromUIEdgeInsets(self.linkBackgroundEdgeInset) forKey:NSStringFromSelector(@selector(linkBackgroundEdgeInset))];
- [coder encodeObject:self.attributedText forKey:NSStringFromSelector(@selector(attributedText))];
- [coder encodeObject:self.text forKey:NSStringFromSelector(@selector(text))];
- }
- - (id)initWithCoder:(NSCoder *)coder {
- self = [super initWithCoder:coder];
- if (!self) {
- return nil;
- }
- [self commonInit];
- if ([coder containsValueForKey:NSStringFromSelector(@selector(enabledTextCheckingTypes))]) {
- self.enabledTextCheckingTypes = [[coder decodeObjectForKey:NSStringFromSelector(@selector(enabledTextCheckingTypes))] unsignedLongLongValue];
- }
- if ([NSMutableParagraphStyle class]) {
- if ([coder containsValueForKey:NSStringFromSelector(@selector(linkAttributes))]) {
- self.linkAttributes = [coder decodeObjectForKey:NSStringFromSelector(@selector(linkAttributes))];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(activeLinkAttributes))]) {
- self.activeLinkAttributes = [coder decodeObjectForKey:NSStringFromSelector(@selector(activeLinkAttributes))];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(inactiveLinkAttributes))]) {
- self.inactiveLinkAttributes = [coder decodeObjectForKey:NSStringFromSelector(@selector(inactiveLinkAttributes))];
- }
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(links))]) {
- NSArray *oldLinks = [coder decodeObjectForKey:NSStringFromSelector(@selector(links))];
- [self addLinksWithTextCheckingResults:oldLinks attributes:nil];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(linkModels))]) {
- self.linkModels = [coder decodeObjectForKey:NSStringFromSelector(@selector(linkModels))];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(shadowRadius))]) {
- self.shadowRadius = [[coder decodeObjectForKey:NSStringFromSelector(@selector(shadowRadius))] floatValue];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(highlightedShadowRadius))]) {
- self.highlightedShadowRadius = [[coder decodeObjectForKey:NSStringFromSelector(@selector(highlightedShadowRadius))] floatValue];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(highlightedShadowOffset))]) {
- self.highlightedShadowOffset = [coder decodeCGSizeForKey:NSStringFromSelector(@selector(highlightedShadowOffset))];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(highlightedShadowColor))]) {
- self.highlightedShadowColor = [coder decodeObjectForKey:NSStringFromSelector(@selector(highlightedShadowColor))];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(kern))]) {
- self.kern = [[coder decodeObjectForKey:NSStringFromSelector(@selector(kern))] floatValue];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(firstLineIndent))]) {
- self.firstLineIndent = [[coder decodeObjectForKey:NSStringFromSelector(@selector(firstLineIndent))] floatValue];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(lineSpacing))]) {
- self.lineSpacing = [[coder decodeObjectForKey:NSStringFromSelector(@selector(lineSpacing))] floatValue];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(minimumLineHeight))]) {
- self.minimumLineHeight = [[coder decodeObjectForKey:NSStringFromSelector(@selector(minimumLineHeight))] floatValue];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(maximumLineHeight))]) {
- self.maximumLineHeight = [[coder decodeObjectForKey:NSStringFromSelector(@selector(maximumLineHeight))] floatValue];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(lineHeightMultiple))]) {
- self.lineHeightMultiple = [[coder decodeObjectForKey:NSStringFromSelector(@selector(lineHeightMultiple))] floatValue];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(textInsets))]) {
- self.textInsets = [coder decodeUIEdgeInsetsForKey:NSStringFromSelector(@selector(textInsets))];
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(verticalAlignment))]) {
- self.verticalAlignment = [coder decodeIntegerForKey:NSStringFromSelector(@selector(verticalAlignment))];
- }
- #pragma clang diagnostic push
- #pragma clang diagnostic ignored "-Wdeprecated-declarations"
- if ([coder containsValueForKey:NSStringFromSelector(@selector(truncationTokenString))]) {
- self.truncationTokenString = [coder decodeObjectForKey:NSStringFromSelector(@selector(truncationTokenString))];
- }
- #pragma clang diagnostic pop
- if ([coder containsValueForKey:NSStringFromSelector(@selector(linkBackgroundEdgeInset))]) {
- self.linkBackgroundEdgeInset = UIEdgeInsetsFromString([coder decodeObjectForKey:NSStringFromSelector(@selector(linkBackgroundEdgeInset))]);
- }
- if ([coder containsValueForKey:NSStringFromSelector(@selector(attributedText))]) {
- self.attributedText = [coder decodeObjectForKey:NSStringFromSelector(@selector(attributedText))];
- } else {
- self.text = super.text;
- }
-
- return self;
- }
- @end
- #pragma mark - TTTAttributedLabelLink
- @implementation TTTAttributedLabelLink
- - (instancetype)initWithAttributes:(NSDictionary *)attributes
- activeAttributes:(NSDictionary *)activeAttributes
- inactiveAttributes:(NSDictionary *)inactiveAttributes
- textCheckingResult:(NSTextCheckingResult *)result {
-
- if ((self = [super init])) {
- _result = result;
- _attributes = [attributes copy];
- _activeAttributes = [activeAttributes copy];
- _inactiveAttributes = [inactiveAttributes copy];
- }
-
- return self;
- }
- - (instancetype)initWithAttributesFromLabel:(TTTAttributedLabel*)label
- textCheckingResult:(NSTextCheckingResult *)result {
-
- return [self initWithAttributes:label.linkAttributes
- activeAttributes:label.activeLinkAttributes
- inactiveAttributes:label.inactiveLinkAttributes
- textCheckingResult:result];
- }
- #pragma mark - Accessibility
- - (NSString *) accessibilityValue {
- if ([_accessibilityValue length] == 0) {
- switch (self.result.resultType) {
- case NSTextCheckingTypeLink:
- _accessibilityValue = self.result.URL.absoluteString;
- break;
- case NSTextCheckingTypePhoneNumber:
- _accessibilityValue = self.result.phoneNumber;
- break;
- case NSTextCheckingTypeDate:
- _accessibilityValue = [NSDateFormatter localizedStringFromDate:self.result.date
- dateStyle:NSDateFormatterLongStyle
- timeStyle:NSDateFormatterLongStyle];
- break;
- default:
- break;
- }
- }
-
- return _accessibilityValue;
- }
- #pragma mark - NSCoding
- - (void)encodeWithCoder:(NSCoder *)aCoder {
- [aCoder encodeObject:self.result forKey:NSStringFromSelector(@selector(result))];
- [aCoder encodeObject:self.attributes forKey:NSStringFromSelector(@selector(attributes))];
- [aCoder encodeObject:self.activeAttributes forKey:NSStringFromSelector(@selector(activeAttributes))];
- [aCoder encodeObject:self.inactiveAttributes forKey:NSStringFromSelector(@selector(inactiveAttributes))];
- [aCoder encodeObject:self.accessibilityValue forKey:NSStringFromSelector(@selector(accessibilityValue))];
- }
- - (id)initWithCoder:(NSCoder *)aDecoder {
- if ((self = [super init])) {
- _result = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(result))];
- _attributes = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(attributes))];
- _activeAttributes = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(activeAttributes))];
- _inactiveAttributes = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(inactiveAttributes))];
- self.accessibilityValue = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(accessibilityValue))];
- }
-
- return self;
- }
- @end
|