forked from omnivector/TTTAttributedLabel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TTTAttributedLabel.m
1131 lines (925 loc) · 48 KB
/
TTTAttributedLabel.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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"
#define kTTTLineBreakWordWrapTextWidthScalingFactor (M_PI / M_E)
NSString * const kTTTStrikeOutAttributeName = @"TTTStrikeOutAttribute";
NSString * const kTTTBaseFontFromLabelAttributeName = @"TTTBaseFontFromLabelAttributeName";
static inline CTTextAlignment CTTextAlignmentFromUITextAlignment(UITextAlignment alignment) {
switch (alignment) {
case UITextAlignmentLeft: return kCTLeftTextAlignment;
case UITextAlignmentCenter: return kCTCenterTextAlignment;
case UITextAlignmentRight: return kCTRightTextAlignment;
default: return kCTNaturalTextAlignment;
}
}
static inline CTLineBreakMode CTLineBreakModeFromUILineBreakMode(UILineBreakMode lineBreakMode) {
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;
}
}
static inline NSTextCheckingType NSTextCheckingTypeFromUIDataDetectorType(UIDataDetectorTypes dataDetectorType) {
NSTextCheckingType textCheckingType = 0;
if (dataDetectorType & UIDataDetectorTypeAddress) {
textCheckingType |= NSTextCheckingTypeAddress;
}
if (dataDetectorType & UIDataDetectorTypeCalendarEvent) {
textCheckingType |= NSTextCheckingTypeDate;
}
if (dataDetectorType & UIDataDetectorTypeLink) {
textCheckingType |= NSTextCheckingTypeLink;
}
if (dataDetectorType & UIDataDetectorTypePhoneNumber) {
textCheckingType |= NSTextCheckingTypePhoneNumber;
}
return textCheckingType;
}
static inline NSDictionary * NSAttributedStringAttributesFromLabel(TTTAttributedLabel *label) {
NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionary];
CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)label.font.fontName, label.font.pointSize, NULL);
[mutableAttributes setObject:(__bridge id)font forKey:(NSString *)kCTFontAttributeName];
CFRelease(font);
[mutableAttributes setObject:@(YES) forKey:(NSString *)kCTForegroundColorFromContextAttributeName];
CTTextAlignment alignment = CTTextAlignmentFromUITextAlignment(label.textAlignment);
CGFloat lineSpacing = label.leading;
CGFloat lineHeightMultiple = label.lineHeightMultiple;
CGFloat topMargin = label.textInsets.top;
CGFloat bottomMargin = label.textInsets.bottom;
CGFloat leftMargin = label.textInsets.left;
CGFloat rightMargin = label.textInsets.right;
CGFloat firstLineIndent = label.firstLineIndent + leftMargin;
CTLineBreakMode lineBreakMode;
if (label.numberOfLines != 1) {
lineBreakMode = CTLineBreakModeFromUILineBreakMode(UILineBreakModeWordWrap);
} else {
lineBreakMode = CTLineBreakModeFromUILineBreakMode(label.lineBreakMode);
}
CTParagraphStyleSetting paragraphStyles[9] = {
{.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 = kCTParagraphStyleSpecifierLineHeightMultiple, .valueSize = sizeof(CGFloat), .value = (const void *)&lineHeightMultiple},
{.spec = kCTParagraphStyleSpecifierFirstLineHeadIndent, .valueSize = sizeof(CGFloat), .value = (const void *)&firstLineIndent},
{.spec = kCTParagraphStyleSpecifierParagraphSpacingBefore, .valueSize = sizeof(CGFloat), .value = (const void *)&topMargin},
{.spec = kCTParagraphStyleSpecifierParagraphSpacing, .valueSize = sizeof(CGFloat), .value = (const void *)&bottomMargin},
{.spec = kCTParagraphStyleSpecifierHeadIndent, .valueSize = sizeof(CGFloat), .value = (const void *)&leftMargin},
{.spec = kCTParagraphStyleSpecifierTailIndent, .valueSize = sizeof(CGFloat), .value = (const void *)&rightMargin}
};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(paragraphStyles, 9);
[mutableAttributes setObject:(__bridge id)paragraphStyle forKey:(NSString *)kCTParagraphStyleAttributeName];
CFRelease(paragraphStyle);
return [NSDictionary dictionaryWithDictionary:mutableAttributes];
}
static inline NSAttributedString * NSAttributedStringByScalingFontSize(NSAttributedString *attributedString, CGFloat scale, CGFloat minimumFontSize) {
if (scale == 1.0f) {
return attributedString;
}
NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy];
[mutableAttributedString enumerateAttribute:(NSString *)kCTFontAttributeName inRange:NSMakeRange(0, [mutableAttributedString length]) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
CTFontRef font = (__bridge CTFontRef)value;
if (font) {
CGFloat scaledFontSize = floorf(CTFontGetSize(font) * scale);
CTFontRef scaledFont = CTFontCreateCopyWithAttributes(font, fmaxf(scaledFontSize, minimumFontSize), NULL, NULL);
CFAttributedStringSetAttribute((__bridge CFMutableAttributedStringRef)mutableAttributedString, CFRangeMake(range.location, range.length), kCTFontAttributeName, scaledFont);
CFRelease(scaledFont);
}
}];
return mutableAttributedString;
}
static inline NSAttributedString * NSAttributedStringBySettingColorFromContext(NSAttributedString *attributedString, UIColor *color) {
if (!color) {
return attributedString;
}
CGColorRef colorRef = color.CGColor;
NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy];
[mutableAttributedString enumerateAttribute:(NSString *)kCTForegroundColorFromContextAttributeName inRange:NSMakeRange(0, [mutableAttributedString length]) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
CFBooleanRef usesColorFromContext = (__bridge CFBooleanRef)value;
if (usesColorFromContext && CFBooleanGetValue(usesColorFromContext)) {
CFRange updateRange = CFRangeMake(range.location, range.length);
CFAttributedStringSetAttribute((__bridge CFMutableAttributedStringRef)mutableAttributedString, updateRange, kCTForegroundColorAttributeName, colorRef);
CFAttributedStringRemoveAttribute((__bridge CFMutableAttributedStringRef)mutableAttributedString, updateRange, kCTForegroundColorFromContextAttributeName);
}
}];
return mutableAttributedString;
}
static inline BOOL CTFontContainsSuffix(CTFontRef font, NSString *suffix) {
if (!font) {
return NO;
}
NSString *familyName = CFBridgingRelease(CTFontCopyName(font, kCTFontFamilyNameKey));
NSString *fontName = CFBridgingRelease(CTFontCopyName(font, kCTFontNameAttribute));
// Special case for system font
if ([familyName isEqual:@".Helvetica NeueUI"]) {
if ([suffix isEqual:@"Medium"]) {
return [fontName isEqual:@".Helvetica NeueUI"];
} else {
return ([suffix length] == 0 || [fontName rangeOfString:suffix].length > 0);
}
} else {
return ([suffix length] == 0 || [fontName rangeOfString:suffix].length > 0);
}
return NO;
}
static inline CTFontRef CTFontCreateCopyWithStyleSuffix(CTFontRef font, NSString *suffix) {
if (!font) {
return NULL;
}
NSString *returnFontName = nil;
NSString *familyName = CFBridgingRelease(CTFontCopyName(font, kCTFontFamilyNameKey));
// Special case for system font
if ([familyName isEqual:@".Helvetica NeueUI"]) {
if ([suffix isEqual:@"Medium"]) {
returnFontName = @".HelveticaNeueUI";
} else {
returnFontName = [@".HelveticaNeueUI-" stringByAppendingString:suffix];
}
} else {
for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {
if (suffix.length == 0 || [fontName rangeOfString:suffix].length > 0) {
if (returnFontName == nil || fontName.length < returnFontName.length) {
returnFontName = fontName;
}
}
}
}
CTFontRef returnFont = NULL;
if (returnFontName) {
returnFont = CTFontCreateWithName((__bridge CFStringRef)returnFontName, CTFontGetSize(font), NULL);
}
return returnFont;
}
static inline CTFontRef CTFontCreateCopyWithStyleSuffixes(CTFontRef font, NSArray *suffixes) {
if (!font) {
return NULL;
}
for (NSString *suffix in suffixes) {
CTFontRef styledFont = CTFontCreateCopyWithStyleSuffix(font, suffix);
if (styledFont) {
return styledFont;
}
}
return NULL;
}
static inline CTFontRef CTFontCreateCopyFromBaseFont(CTFontRef font, CTFontRef baseFont) {
if (!font) {
CFRetain(baseFont);
return baseFont;
}
BOOL isBold = NO;
BOOL isItalic = NO;
NSArray *boldItalicSuffixes = [NSArray arrayWithObjects:@"BoldItalic", @"BoldOblique", @"BlackItalic", nil];
NSArray *boldSuffixes = nil;
NSArray *italicSuffixes = nil;
CTFontRef adjustedfont = NULL;
// Check for Bold & Italic first
for (NSString *suffix in boldItalicSuffixes) {
if (CTFontContainsSuffix(font, suffix)) {
isBold = YES;
isItalic = YES;
break;
}
}
if (!isBold && !isItalic) {
boldSuffixes = [NSArray arrayWithObjects:@"Bold", @"Black", nil];
// If that fails, check for Bold
for (NSString *suffix in boldSuffixes) {
if (CTFontContainsSuffix(font, suffix)) {
isBold = YES;
break;
}
}
// If that fails, check for Italic
if (!isBold) {
italicSuffixes = [NSArray arrayWithObjects:@"Italic", @"Oblique", nil];
for (NSString *suffix in italicSuffixes) {
if (CTFontContainsSuffix(font, suffix)) {
isItalic = YES;
break;
}
}
}
}
if (isBold && isItalic) {
adjustedfont = CTFontCreateCopyWithStyleSuffixes(baseFont, boldItalicSuffixes);
} else if (isBold) {
adjustedfont = CTFontCreateCopyWithStyleSuffixes(baseFont, boldSuffixes);
} else if (isItalic) {
adjustedfont = CTFontCreateCopyWithStyleSuffixes(baseFont, italicSuffixes);
} else {
NSArray *normalSuffixes = [NSArray arrayWithObjects:@"Medium", @"", nil];
adjustedfont = CTFontCreateCopyWithStyleSuffixes(baseFont, normalSuffixes);
}
return adjustedfont;
}
static inline NSAttributedString * NSAttributedStringBySettingFontFromBaseFont(NSAttributedString *attributedString, UIFont *baseFont) {
if (!baseFont) {
return attributedString;
}
CTFontRef baseFontRef = CTFontCreateWithName((__bridge CFStringRef)baseFont.fontName, baseFont.pointSize, NULL);
NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy];
[mutableAttributedString enumerateAttribute:kTTTBaseFontFromLabelAttributeName inRange:NSMakeRange(0, [mutableAttributedString length]) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
CFBooleanRef usesFontFromLabel = (__bridge CFBooleanRef)value;
if (usesFontFromLabel && CFBooleanGetValue(usesFontFromLabel)) {
CFRange updateRange;
NSRange effectiveRange;
CTFontRef currentFont = (__bridge CTFontRef)[mutableAttributedString attribute:(NSString *)kCTFontAttributeName atIndex:range.location effectiveRange:&effectiveRange];
if (currentFont) {
updateRange = CFRangeMake(effectiveRange.location, effectiveRange.length);
} else {
updateRange = CFRangeMake(range.location, range.length);
}
// There's a chance the adjusted font could have come back as NULL if we couldn't find a sylized version of the base font
CTFontRef adjustedFont = CTFontCreateCopyFromBaseFont(currentFont, baseFontRef);
if (adjustedFont) {
CFAttributedStringSetAttribute((__bridge CFMutableAttributedStringRef)mutableAttributedString, updateRange, kCTFontAttributeName, adjustedFont);
CFRelease(adjustedFont);
}
CFAttributedStringRemoveAttribute((__bridge CFMutableAttributedStringRef)mutableAttributedString, CFRangeMake(range.location, range.length), (__bridge CFStringRef)kTTTBaseFontFromLabelAttributeName);
}
}];
CFRelease(baseFontRef);
return mutableAttributedString;
}
// TODO: Kill this once we have font inheritance working.
static inline NSAttributedString * NSAttributedStringByReplacingFontWithFont(NSAttributedString *attributedString, UIFont *font) {
if (!font) {
return attributedString;
}
CTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);
NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy];
[mutableAttributedString enumerateAttribute:(NSString *)kCTFontAttributeName inRange:NSMakeRange(0, [mutableAttributedString length]) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
CFAttributedStringSetAttribute((__bridge CFMutableAttributedStringRef)mutableAttributedString, CFRangeMake(range.location, range.length), kCTFontAttributeName, fontRef);
}];
CFRelease(fontRef);
return mutableAttributedString;
}
@interface TTTAttributedLabel ()
@property (readwrite, nonatomic, copy) NSAttributedString *attributedText;
@property (readwrite, nonatomic, copy) NSAttributedString *inactiveAttributedText;
@property (readwrite, nonatomic, copy) NSAttributedString *renderedAttributedText;
@property (readwrite, nonatomic, assign) CTFramesetterRef framesetter;
@property (readwrite, nonatomic, assign) CTFramesetterRef highlightFramesetter;
@property (readwrite, nonatomic, strong) NSDataDetector *dataDetector;
@property (readwrite, nonatomic, strong) NSArray *links;
@property (readwrite, nonatomic, strong) NSTextCheckingResult *activeLink;
@property (readwrite, nonatomic, assign) CGFloat textScaleFactor;
@property (readwrite, nonatomic, assign) BOOL plainText;
- (void)commonInit;
- (void)setNeedsFramesetter;
- (void)setTextAndParseLinks:(NSAttributedString *)attributedText;
- (NSArray *)detectedLinksInString:(NSString *)string range:(NSRange)range error:(NSError **)error;
- (NSTextCheckingResult *)linkAtCharacterIndex:(CFIndex)idx;
- (NSTextCheckingResult *)linkAtPoint:(CGPoint)p;
- (CFIndex)characterIndexAtPoint:(CGPoint)p;
- (void)drawFramesetter:(CTFramesetterRef)framesetter textRange:(CFRange)textRange inRect:(CGRect)rect context:(CGContextRef)c;
- (void)drawStrike:(CTFrameRef)frame inRect:(CGRect)rect context:(CGContextRef)c;
@end
@implementation TTTAttributedLabel {
@private
BOOL _needsFramesetter;
}
@dynamic text;
@synthesize attributedText = _attributedText;
@synthesize inactiveAttributedText = _inactiveAttributedText;
@synthesize renderedAttributedText = _renderedAttributedText;
@synthesize framesetter = _framesetter;
@synthesize highlightFramesetter = _highlightFramesetter;
@synthesize delegate = _delegate;
@synthesize dataDetectorTypes = _dataDetectorTypes;
@synthesize dataDetector = _dataDetector;
@synthesize links = _links;
@synthesize linkAttributes = _linkAttributes;
@synthesize activeLinkAttributes = _activeLinkAttributes;
@synthesize shadowRadius = _shadowRadius;
@synthesize leading = _leading;
@synthesize lineHeightMultiple = _lineHeightMultiple;
@synthesize firstLineIndent = _firstLineIndent;
@synthesize textInsets = _textInsets;
@synthesize verticalAlignment = _verticalAlignment;
@synthesize activeLink = _activeLink;
@synthesize textScaleFactor = _textScaleFactor;
@synthesize plainText = _plainText;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (!self) {
return nil;
}
[self commonInit];
return self;
}
- (id)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (!self) {
return nil;
}
[self commonInit];
return self;
}
- (void)commonInit {
self.dataDetectorTypes = UIDataDetectorTypeNone;
self.links = [NSArray array];
NSMutableDictionary *mutableLinkAttributes = [NSMutableDictionary dictionary];
[mutableLinkAttributes setValue:(id)[[UIColor blueColor] CGColor] forKey:(NSString*)kCTForegroundColorAttributeName];
[mutableLinkAttributes setValue:[NSNumber numberWithBool:YES] forKey:(NSString *)kCTUnderlineStyleAttributeName];
self.linkAttributes = [NSDictionary dictionaryWithDictionary:mutableLinkAttributes];
NSMutableDictionary *mutableActiveLinkAttributes = [NSMutableDictionary dictionary];
[mutableActiveLinkAttributes setValue:(id)[[UIColor redColor] CGColor] forKey:(NSString*)kCTForegroundColorAttributeName];
[mutableActiveLinkAttributes setValue:[NSNumber numberWithBool:YES] forKey:(NSString *)kCTUnderlineStyleAttributeName];
self.activeLinkAttributes = [NSDictionary dictionaryWithDictionary:mutableActiveLinkAttributes];
self.textInsets = UIEdgeInsetsZero;
self.textScaleFactor = 1.0f;
self.userInteractionEnabled = YES;
self.multipleTouchEnabled = NO;
}
- (void)dealloc {
if (_framesetter) CFRelease(_framesetter);
if (_highlightFramesetter) CFRelease(_highlightFramesetter);
}
#pragma mark -
- (void)setAttributedText:(NSAttributedString *)text {
if ([text isEqualToAttributedString:self.attributedText]) {
return;
}
[self willChangeValueForKey:@"attributedText"];
_attributedText = [text copy];
[self didChangeValueForKey:@"attributedText"];
[self setNeedsFramesetter];
}
- (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) {
if (_framesetter) CFRelease(_framesetter);
if (_highlightFramesetter) CFRelease(_highlightFramesetter);
self.framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)self.renderedAttributedText);
self.highlightFramesetter = nil;
_needsFramesetter = NO;
}
}
return _framesetter;
}
- (NSAttributedString *)renderedAttributedText {
if (!_renderedAttributedText) {
// Inherit the label's font
NSAttributedString *adjustedString = NSAttributedStringBySettingFontFromBaseFont(self.attributedText, self.font);
// Inherit the label's textColor
adjustedString = NSAttributedStringBySettingColorFromContext(adjustedString, self.textColor);
// Adjust the the scale for drawing
adjustedString = NSAttributedStringByScalingFontSize(adjustedString, self.textScaleFactor, self.minimumFontSize);
self.renderedAttributedText = adjustedString;
}
return _renderedAttributedText;
}
- (void)setTextScaleFactor:(CGFloat)textScaleFactor {
if (textScaleFactor != _textScaleFactor) {
_textScaleFactor = textScaleFactor;
// Give the rendered text a chance to regenerate, but don't redraw since this is an internal adjustment method
[self setNeedsFramesetter];
}
}
#pragma mark -
- (void)setLinkActive:(BOOL)active withTextCheckingResult:(NSTextCheckingResult *)result {
if (result && [self.activeLinkAttributes count] > 0) {
if (active) {
if (!self.inactiveAttributedText) {
self.inactiveAttributedText = self.attributedText;
}
NSMutableAttributedString *mutableAttributedString = [self.inactiveAttributedText mutableCopy];
[mutableAttributedString addAttributes:self.activeLinkAttributes range:result.range];
self.attributedText = mutableAttributedString;
[self setNeedsDisplay];
} else {
if (self.inactiveAttributedText) {
self.attributedText = self.inactiveAttributedText;
self.inactiveAttributedText = nil;
[self setNeedsDisplay];
}
}
}
}
#pragma mark -
- (void)setDataDetectorTypes:(UIDataDetectorTypes)dataDetectorTypes {
[self willChangeValueForKey:@"dataDetectorTypes"];
_dataDetectorTypes = dataDetectorTypes;
[self didChangeValueForKey:@"dataDetectorTypes"];
if (self.dataDetectorTypes != UIDataDetectorTypeNone) {
self.dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeFromUIDataDetectorType(self.dataDetectorTypes) error:nil];
}
}
- (NSArray *)detectedLinksInString:(NSString *)string range:(NSRange)range error:(NSError **)error {
if (!string || !self.dataDetector) {
return [NSArray array];
}
NSMutableArray *mutableLinks = [NSMutableArray array];
[self.dataDetector enumerateMatchesInString:string options:0 range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
[mutableLinks addObject:result];
}];
return [NSArray arrayWithArray:mutableLinks];
}
- (void)addLinkWithTextCheckingResult:(NSTextCheckingResult *)result attributes:(NSDictionary *)attributes {
self.links = [self.links arrayByAddingObject:result];
if (attributes) {
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
[mutableAttributedString addAttributes:attributes range:result.range];
self.attributedText = mutableAttributedString;
}
}
- (void)addLinkWithTextCheckingResult:(NSTextCheckingResult *)result {
[self addLinkWithTextCheckingResult:result attributes:self.linkAttributes];
}
- (void)addLinkToURL:(NSURL *)url withRange:(NSRange)range {
[self addLinkWithTextCheckingResult:[NSTextCheckingResult linkCheckingResultWithRange:range URL:url]];
}
- (void)addLinkToAddress:(NSDictionary *)addressComponents withRange:(NSRange)range {
[self addLinkWithTextCheckingResult:[NSTextCheckingResult addressCheckingResultWithRange:range components:addressComponents]];
}
- (void)addLinkToPhoneNumber:(NSString *)phoneNumber withRange:(NSRange)range {
[self addLinkWithTextCheckingResult:[NSTextCheckingResult phoneNumberCheckingResultWithRange:range phoneNumber:phoneNumber]];
}
- (void)addLinkToDate:(NSDate *)date withRange:(NSRange)range {
[self addLinkWithTextCheckingResult:[NSTextCheckingResult dateCheckingResultWithRange:range date:date]];
}
- (void)addLinkToDate:(NSDate *)date timeZone:(NSTimeZone *)timeZone duration:(NSTimeInterval)duration withRange:(NSRange)range {
[self addLinkWithTextCheckingResult:[NSTextCheckingResult dateCheckingResultWithRange:range date:date timeZone:timeZone duration:duration]];
}
#pragma mark -
- (NSTextCheckingResult *)linkAtCharacterIndex:(CFIndex)idx {
for (NSTextCheckingResult *result in self.links) {
NSRange range = result.range;
if ((CFIndex)range.location <= idx && idx <= (CFIndex)(range.location + range.length - 1)) {
return result;
}
}
return nil;
}
- (NSTextCheckingResult *)linkAtPoint:(CGPoint)p {
CFIndex idx = [self characterIndexAtPoint:p];
return [self linkAtCharacterIndex:idx];
}
- (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, [self.renderedAttributedText 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;
}
NSUInteger idx = NSNotFound;
CGPoint lineOrigins[numberOfLines];
CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), lineOrigins);
for (CFIndex lineIndex = 0; lineIndex < numberOfLines; lineIndex++) {
CGPoint lineOrigin = lineOrigins[lineIndex];
CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex);
// Get bounding information of line
CGFloat ascent, descent, leading, width;
width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
CGFloat yMin = floor(lineOrigin.y - descent);
CGFloat yMax = ceil(lineOrigin.y + ascent);
// 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;
}
- (void)drawFramesetter:(CTFramesetterRef)framesetter textRange:(CFRange)textRange inRect:(CGRect)rect context:(CGContextRef)c {
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, rect);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, textRange, path, NULL);
CFArrayRef lines = CTFrameGetLines(frame);
NSInteger numberOfLines = self.numberOfLines > 0 ? MIN(self.numberOfLines, CFArrayGetCount(lines)) : CFArrayGetCount(lines);
BOOL truncateLastLine = (self.lineBreakMode == UILineBreakModeHeadTruncation || self.lineBreakMode == UILineBreakModeMiddleTruncation || self.lineBreakMode == UILineBreakModeTailTruncation);
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);
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;
NSUInteger truncationAttributePosition = lastLineRange.location;
UILineBreakMode lineBreakMode = self.lineBreakMode;
// Multiple lines, only use UILineBreakModeTailTruncation
if (numberOfLines != 1) {
lineBreakMode = UILineBreakModeTailTruncation;
}
switch (lineBreakMode) {
case UILineBreakModeHeadTruncation:
truncationType = kCTLineTruncationStart;
break;
case UILineBreakModeMiddleTruncation:
truncationType = kCTLineTruncationMiddle;
truncationAttributePosition += (lastLineRange.length / 2);
break;
case UILineBreakModeTailTruncation:
default:
truncationType = kCTLineTruncationEnd;
truncationAttributePosition += (lastLineRange.length - 1);
break;
}
// Get the attributes and use them to create the truncation token string
NSDictionary *tokenAttributes = [self.renderedAttributedText attributesAtIndex:truncationAttributePosition effectiveRange:NULL];
// \u2026 is the Unicode horizontal ellipsis character code
NSAttributedString *tokenString = [[NSAttributedString alloc] initWithString:@"\u2026" attributes:tokenAttributes];
CTLineRef truncationToken = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)tokenString);
// Append truncationToken to the string
// because if string isn't too long, CT wont add the truncationToken on it's own
// There is no change of a double truncationToken because CT only add the token if it removes characters (and the one we add will go first)
NSMutableAttributedString *truncationString = [[self.renderedAttributedText attributedSubstringFromRange:NSMakeRange(lastLineRange.location, lastLineRange.length)] mutableCopy];
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:lastLineRange.length - 1];
if ([[NSCharacterSet newlineCharacterSet] characterIsMember:lastCharacter]) {
[truncationString deleteCharactersInRange:NSMakeRange(lastLineRange.length - 1, 1)];
}
}
[truncationString appendAttributedString:tokenString];
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);
}
CTLineDraw(truncatedLine, c);
CFRelease(truncatedLine);
CFRelease(truncationLine);
CFRelease(truncationToken);
} else {
CTLineDraw(line, c);
}
} else {
CTLineDraw(line, c);
}
}
[self drawStrike:frame inRect:rect context:c];
CFRelease(frame);
CFRelease(path);
}
- (void)drawStrike:(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) {
CGRect lineBounds = CTLineGetImageBounds((__bridge CTLineRef)line, c);
lineBounds.origin.x = origins[lineIndex].x;
lineBounds.origin.y = origins[lineIndex].y;
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 ascent = 0.0f;
CGFloat descent = 0.0f;
runBounds.size.width = CTRunGetTypographicBounds((__bridge CTRunRef)glyphRun, CFRangeMake(0, 0), &ascent, &descent, NULL);
runBounds.size.height = ascent + descent;
CGFloat xOffset = CTLineGetOffsetForStringIndex((__bridge CTLineRef)line, CTRunGetStringRange((__bridge CTRunRef)glyphRun).location, NULL);
runBounds.origin.x = origins[lineIndex].x + rect.origin.x + xOffset;
runBounds.origin.y = origins[lineIndex].y + rect.origin.y;
runBounds.origin.y -= descent;
// Don't draw strikeout too far to the right
if (CGRectGetWidth(runBounds) > CGRectGetWidth(lineBounds)) {
runBounds.size.width = CGRectGetWidth(lineBounds);
}
switch (superscriptStyle) {
case 1:
runBounds.origin.y -= ascent * 0.47f;
break;
case -1:
runBounds.origin.y += ascent * 0.25f;
break;
default:
break;
}
// Use text color, or default to black
id color = [attributes objectForKey:(id)kCTForegroundColorAttributeName];
if (color) {
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));
CGFloat y = roundf(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);
CFRelease(font);
}
}
lineIndex++;
}
}
#pragma mark - TTTAttributedLabel
- (void)setText:(id)text {
if ([text isKindOfClass:[NSString class]]) {
[self setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:nil];
} else if ([text isKindOfClass:[NSAttributedString class]]) {
[self setTextAndParseLinks:text];
}
}
- (void)setTextAndParseLinks:(NSAttributedString *)attributedText {
self.attributedText = attributedText;
self.links = [NSArray array];
if (self.dataDetectorTypes != UIDataDetectorTypeNone) {
for (NSTextCheckingResult *result in [self detectedLinksInString:[self.attributedText string] range:NSMakeRange(0, [attributedText length]) error:nil]) {
[self addLinkWithTextCheckingResult:result];
}
}
[super setText:[self.attributedText string]];
}
- (void)setText:(id)text afterInheritingLabelAttributesAndConfiguringWithBlock:(NSMutableAttributedString *(^)(NSMutableAttributedString *mutableAttributedString))block {
NSMutableAttributedString *mutableAttributedString = nil;
if ([text isKindOfClass:[NSString class]]) {
self.plainText = YES;
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 setTextAndParseLinks:mutableAttributedString];
}
#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];
}
}
- (void)setFont:(UIFont *)font {
UIFont *oldFont = self.font;
[super setFont:font];
// Redraw to allow any BaseFontFromLabel attributes a chance to update
if (font != oldFont) {
// TODO: Kill this once we have font inheritance working.
if (self.plainText) {
[self setTextAndParseLinks:NSAttributedStringByReplacingFontWithFont(self.attributedText, font)];
}
[self setNeedsFramesetter];
[self setNeedsDisplay];
}
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
if (!self.renderedAttributedText) {
return [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
}
CGRect textRect = bounds;
// Adjust the text to be in the center vertically, if the text size is smaller than bounds
CGSize textSize = CTFramesetterSuggestFrameSizeWithConstraints(self.framesetter, CFRangeMake(0, [self.renderedAttributedText length]), NULL, bounds.size, NULL);
textSize = CGSizeMake(ceilf(textSize.width), ceilf(textSize.height)); // Fix for iOS 4, CTFramesetterSuggestFrameSizeWithConstraints sometimes returns fractional sizes
if (textSize.height < textRect.size.height) {
CGFloat heightChange = (textRect.size.height - textSize.height);
CGFloat yOffset = 0.0f;
switch (self.verticalAlignment) {
case TTTAttributedLabelVerticalAlignmentTop:
heightChange = 0.0f;
break;
case TTTAttributedLabelVerticalAlignmentCenter:
yOffset = floorf((textRect.size.height - textSize.height) / 2.0f);
break;
case TTTAttributedLabelVerticalAlignmentBottom:
yOffset = textRect.size.height - textSize.height;
break;
}
textRect.origin.y += yOffset;
textRect.size = CGSizeMake(textRect.size.width, textRect.size.height - heightChange + yOffset);
}
return textRect;
}
- (void)drawTextInRect:(CGRect)rect {
if (!self.renderedAttributedText) {
[super drawTextInRect:rect];
return;
}
// Adjust the font size to fit width, if necessarry
if (self.adjustsFontSizeToFitWidth && self.numberOfLines > 0) {
CGFloat textWidth = [self sizeThatFits:CGSizeZero].width;
CGFloat availableWidth = self.frame.size.width * self.numberOfLines;
if (self.numberOfLines > 1 && self.lineBreakMode == UILineBreakModeWordWrap) {
textWidth *= kTTTLineBreakWordWrapTextWidthScalingFactor;
}
if (textWidth > availableWidth && textWidth > 0.0f) {
self.textScaleFactor = (availableWidth / textWidth);
} else {
self.textScaleFactor = 1.0f;
}
} else {
self.textScaleFactor = 1.0f;
}
CGContextRef c = UIGraphicsGetCurrentContext();
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, rect.size.height);
CGContextScaleCTM(c, 1.0f, -1.0f);
CFRange textRange = CFRangeMake(0, [self.renderedAttributedText length]);
// First, get the text rect (which takes vertical centering into account)
CGRect textRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
// CoreText draws it's text aligned to the bottom, so we move the CTM here to take our vertical offsets into account
CGContextTranslateCTM(c, 0.0f, rect.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]);
}
// Finally, draw the text or highlighted text itself (on top of the shadow, if there is one)
if (self.highlightedTextColor && self.highlighted) {
if (!self.highlightFramesetter) {
NSMutableAttributedString *mutableAttributedString = [self.renderedAttributedText mutableCopy];
[mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[self.highlightedTextColor CGColor] range:NSMakeRange(0, mutableAttributedString.length)];
self.highlightFramesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)mutableAttributedString);
}
[self drawFramesetter:self.highlightFramesetter textRange:textRange inRect:textRect context:c];
} else {
[self drawFramesetter:self.framesetter textRange:textRange inRect:textRect context:c];
}