This repository has been archived by the owner on May 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
NIAttributedLabel.m
1788 lines (1385 loc) · 66.6 KB
/
NIAttributedLabel.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
//
// Copyright 2011 Roger Chapman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "NIAttributedLabel.h"
#import "NimbusCore.h"
#import "NSMutableAttributedString+NimbusAttributedLabel.h"
#import <QuartzCore/QuartzCore.h>
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "Nimbus requires ARC support."
#endif
static const CGFloat kVMargin = 5.0f;
static const NSTimeInterval kLongPressTimeInterval = 0.5;
static const CGFloat kLongPressGutter = 22;
NSString * const kNILinkAttributeName = @"NIAttributedLabel:Link";
CGFloat ImageDelegateGetAscentCallback(void* refCon);
CGFloat ImageDelegateGetDescentCallback(void* refCon);
CGFloat ImageDelegateGetWidthCallback(void* refCon);
// \u2026 is the Unicode horizontal ellipsis character code
static NSString* const kEllipsesCharacter = @"\u2026";
// The touch gutter is the amount of space around a link that will still register as tapping
// "within" the link.
static const CGFloat kTouchGutter = 22;
CGSize NISizeOfAttributedStringConstrainedToSize(NSAttributedString *attributedString, CGSize size, NSInteger numberOfLines) {
if (nil == attributedString) {
return CGSizeZero;
}
CFAttributedStringRef attributedStringRef = (__bridge CFAttributedStringRef)attributedString;
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attributedStringRef);
CFRange range = CFRangeMake(0, 0);
// This logic adapted from @mattt's TTTAttributedLabel
// https://github.com/mattt/TTTAttributedLabel
if (numberOfLines > 0 && nil != framesetter) {
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0, 0, size.width, size.height));
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
CFArrayRef lines = CTFrameGetLines(frame);
if (nil != lines && CFArrayGetCount(lines) > 0) {
NSInteger lastVisibleLineIndex = MIN(numberOfLines, CFArrayGetCount(lines)) - 1;
CTLineRef lastVisibleLine = CFArrayGetValueAtIndex(lines, lastVisibleLineIndex);
CFRange rangeToLayout = CTLineGetStringRange(lastVisibleLine);
range = CFRangeMake(0, rangeToLayout.location + rangeToLayout.length);
}
CFRelease(frame);
CFRelease(path);
}
CFRange fitCFRange = CFRangeMake(0, 0);
CGSize newSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, range, NULL, size, &fitCFRange);
if (nil != framesetter) {
CFRelease(framesetter);
framesetter = nil;
}
return CGSizeMake(ceilf(newSize.width), ceilf(newSize.height));
}
@interface NIAttributedLabelImage : NSObject
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, NI_STRONG) UIImage* image;
@property (nonatomic, assign) UIEdgeInsets margins;
@property (nonatomic, assign, readonly) CGSize boxSize; // imageSize + margins
@property (nonatomic, assign) NIVerticalTextAlignment verticalTextAlignment;
@property (nonatomic, assign) CGFloat fontAscent;
@property (nonatomic, assign) CGFloat fontDescent;
@end
@implementation NIAttributedLabelImage
@synthesize index;
@synthesize image;
@synthesize margins;
@synthesize verticalTextAlignment;
@synthesize fontAscent;
@synthesize fontDescent;
- (CGSize)boxSize
{
return CGSizeMake(self.image.size.width + self.margins.left + self.margins.right,
self.image.size.height + self.margins.top + self.margins.bottom);
}
@end
@interface NIAttributedLabel() <UIActionSheetDelegate>
@property (nonatomic, NI_STRONG) NSMutableAttributedString* mutableAttributedString;
@property (nonatomic, assign) CTFrameRef textFrame;
@property (assign) BOOL detectingLinks; // Atomic.
@property (nonatomic, assign) BOOL linksHaveBeenDetected;
@property (nonatomic, copy) NSArray* detectedlinkLocations;
@property (nonatomic, NI_STRONG) NSMutableArray* explicitLinkLocations;
@property (nonatomic, NI_STRONG) NSTextCheckingResult* originalLink;
@property (nonatomic, NI_STRONG) NSTextCheckingResult* touchedLink;
@property (nonatomic, NI_STRONG) NSTimer* longPressTimer;
@property (nonatomic, assign) CGPoint touchPoint;
@property (nonatomic, NI_STRONG) NSTextCheckingResult* actionSheetLink;
@property (nonatomic, NI_STRONG) NSArray *accessibleElements;
@property (nonatomic, NI_STRONG) NSMutableArray *images;
@end
@interface NIAttributedLabel(ConversionUtilities)
#if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_6_0
+ (CTTextAlignment)alignmentFromUITextAlignment:(UITextAlignment)alignment;
+ (CTLineBreakMode)lineBreakModeFromUILineBreakMode:(NSLineBreakMode)lineBreakMode;
#else
+ (CTTextAlignment)alignmentFromUITextAlignment:(NSTextAlignment)alignment;
+ (CTLineBreakMode)lineBreakModeFromUILineBreakMode:(NSLineBreakMode)lineBreakMode;
#endif
+ (NSMutableAttributedString *)mutableAttributedStringFromLabel:(UILabel *)label;
@end
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
@implementation NIAttributedLabel
@synthesize mutableAttributedString = _mutableAttributedString;
@synthesize textFrame = _textFrame;
@synthesize detectingLinks = _detectingLinks;
@synthesize linksHaveBeenDetected = _linksHaveBeenDetected;
@synthesize detectedlinkLocations = _detectedlinkLocations;
@synthesize explicitLinkLocations = _explicitLinkLocations;
@synthesize originalLink = _originalLink;
@synthesize touchedLink = _touchedLink;
@synthesize longPressTimer = _longPressTimer;
@synthesize touchPoint = _touchPoint;
@synthesize actionSheetLink = _actionSheetLink;
@synthesize accessibleElements = _accessibleElements;
@synthesize autoDetectLinks = _autoDetectLinks;
@synthesize deferLinkDetection = _deferLinkDetection;
@synthesize dataDetectorTypes = _dataDetectorTypes;
@synthesize verticalTextAlignment = _verticalTextAlignment;
@synthesize underlineStyle = _underlineStyle;
@synthesize underlineStyleModifier = _underlineStyleModifier;
@synthesize shadowBlur;
@synthesize strokeWidth = _strokeWidth;
@synthesize strokeColor = _strokeColor;
@synthesize textKern = _textKern;
@synthesize linkColor = _linkColor;
@synthesize highlightedLinkBackgroundColor = _highlightedLinkBackgroundColor;
@synthesize linksHaveUnderlines = _linksHaveUnderlines;
@synthesize attributesForLinks = _attributesForLinks;
@synthesize attributesForHighlightedLink = _attributesForHighlightedLink;
@synthesize lineHeight = _lineHeight;
@synthesize images;
@synthesize delegate = _delegate;
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)dealloc {
[_longPressTimer invalidate];
if (nil != _textFrame) {
CFRelease(_textFrame);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)_configureDefaults {
self.verticalTextAlignment = NIVerticalTextAlignmentTop;
self.linkColor = [UIColor blueColor];
self.dataDetectorTypes = NSTextCheckingTypeLink;
self.highlightedLinkBackgroundColor = [UIColor colorWithWhite:0.5f alpha:0.5f];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self _configureDefaults];
}
return self;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)awakeFromNib {
[super awakeFromNib];
[self _configureDefaults];
NSMutableAttributedString* attributedText = [[self class] mutableAttributedStringFromLabel:self];
#if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_6_0
self.attributedString = attributedText;
#else
self.attributedText = attributedText;
#endif
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)resetTextFrame {
if (nil != self.textFrame) {
CFRelease(self.textFrame);
self.textFrame = nil;
}
self.accessibleElements = nil;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)attributedTextDidChange {
[self resetTextFrame];
[self setNeedsDisplay];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setFrame:(CGRect)frame {
BOOL frameDidChange = !CGRectEqualToRect(self.frame, frame);
[super setFrame:frame];
if (frameDidChange) {
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGSize)sizeThatFits:(CGSize)size {
if (nil == self.mutableAttributedString) {
return CGSizeZero;
}
return NISizeOfAttributedStringConstrainedToSize([self mutableAttributedStringWithAdditions], size, self.numberOfLines);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Public Methods
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setText:(NSString *)text {
[super setText:text];
NSMutableAttributedString* attributedText = [[self class] mutableAttributedStringFromLabel:self];
#if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_6_0
self.attributedString = attributedText;
#else
self.attributedText = attributedText;
#endif
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Deprecated method.
- (NSAttributedString *)attributedString {
return [self.mutableAttributedString copy];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= NIIOS_6_0
- (NSAttributedString *)attributedText {
return [self.mutableAttributedString copy];
}
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setAttributedString:(NSAttributedString *)attributedText {
if (self.mutableAttributedString != attributedText) {
self.mutableAttributedString = [attributedText mutableCopy];
// Clear the link caches.
self.detectedlinkLocations = nil;
self.linksHaveBeenDetected = NO;
[self removeAllExplicitLinks];
// Remove all images.
self.images = nil;
// Pull any explicit links from the attributed string itself
[self _processLinksInAttributedString:self.mutableAttributedString];
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= NIIOS_6_0
- (void)setAttributedText:(NSAttributedString *)attributedText {
if (self.mutableAttributedString != attributedText) {
self.mutableAttributedString = [attributedText mutableCopy];
// Clear the link caches.
self.detectedlinkLocations = nil;
self.linksHaveBeenDetected = NO;
[self removeAllExplicitLinks];
// Remove all images.
self.images = nil;
// Pull any explicit links from the attributed string itself
[self _processLinksInAttributedString:self.mutableAttributedString];
[self attributedTextDidChange];
}
}
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setAutoDetectLinks:(BOOL)autoDetectLinks {
_autoDetectLinks = autoDetectLinks;
[self attributedTextDidChange];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)addLink:(NSURL *)urlLink range:(NSRange)range {
if (nil == self.explicitLinkLocations) {
self.explicitLinkLocations = [[NSMutableArray alloc] init];
}
NSTextCheckingResult* result = [NSTextCheckingResult linkCheckingResultWithRange:range URL:urlLink];
[self.explicitLinkLocations addObject:result];
[self attributedTextDidChange];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)removeAllExplicitLinks {
self.explicitLinkLocations = nil;
[self attributedTextDidChange];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_6_0
- (void)setTextAlignment:(UITextAlignment)textAlignment {
// UILabel doesn't implement UITextAlignmentJustify, so we can't call super when this is the case
// or the app will crash.
if (textAlignment != UITextAlignmentJustify) {
// We assume that the UILabel implementation will call setNeedsDisplay. Where we don't call super
// we call setNeedsDisplay ourselves.
[super setTextAlignment:textAlignment];
}
if (nil != self.mutableAttributedString) {
CTTextAlignment alignment = [self.class alignmentFromUITextAlignment:textAlignment];
CTLineBreakMode lineBreak = [self.class lineBreakModeFromUILineBreakMode:self.lineBreakMode];
[self.mutableAttributedString setTextAlignment:alignment lineBreakMode:lineBreak lineHeight:self.lineHeight];
}
}
#else
- (void)setTextAlignment:(NSTextAlignment)textAlignment {
// We assume that the UILabel implementation will call setNeedsDisplay. Where we don't call super
// we call setNeedsDisplay ourselves.
if (NSTextAlignmentJustified == textAlignment) {
// iOS 6.0 Beta 2 crashes when using justified text alignments for some reason.
[super setTextAlignment:NSTextAlignmentLeft];
} else {
[super setTextAlignment:textAlignment];
}
if (nil != self.mutableAttributedString) {
CTTextAlignment alignment = [self.class alignmentFromUITextAlignment:textAlignment];
CTLineBreakMode lineBreak = [self.class lineBreakModeFromUILineBreakMode:self.lineBreakMode];
[self.mutableAttributedString setTextAlignment:alignment lineBreakMode:lineBreak lineHeight:self.lineHeight];
}
}
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////
#if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_6_0
- (void)setLineBreakMode:(NSLineBreakMode)lineBreakMode {
[super setLineBreakMode:lineBreakMode];
if (nil != self.mutableAttributedString) {
CTTextAlignment alignment = [self.class alignmentFromUITextAlignment:self.textAlignment];
CTLineBreakMode lineBreak = [self.class lineBreakModeFromUILineBreakMode:lineBreakMode];
[self.mutableAttributedString setTextAlignment:alignment lineBreakMode:lineBreak lineHeight:self.lineHeight];
}
}
#else
- (void)setLineBreakMode:(NSLineBreakMode)lineBreakMode {
[super setLineBreakMode:lineBreakMode];
if (nil != self.mutableAttributedString) {
CTTextAlignment alignment = [self.class alignmentFromUITextAlignment:self.textAlignment];
CTLineBreakMode lineBreak = [self.class lineBreakModeFromUILineBreakMode:lineBreakMode];
[self.mutableAttributedString setTextAlignment:alignment lineBreakMode:lineBreak lineHeight:self.lineHeight];
}
}
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTextColor:(UIColor *)textColor {
[super setTextColor:textColor];
[self.mutableAttributedString setTextColor:textColor];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTextColor:(UIColor *)textColor range:(NSRange)range {
[self.mutableAttributedString setTextColor:textColor range:range];
[self attributedTextDidChange];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setFont:(UIFont *)font {
[super setFont:font];
[self.mutableAttributedString setFont:font];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setFont:(UIFont *)font range:(NSRange)range {
[self.mutableAttributedString setFont:font range:range];
[self attributedTextDidChange];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setUnderlineStyle:(CTUnderlineStyle)style {
if (style != _underlineStyle) {
_underlineStyle = style;
[self.mutableAttributedString setUnderlineStyle:style modifier:self.underlineStyleModifier];
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setUnderlineStyleModifier:(CTUnderlineStyleModifiers)modifier {
if (modifier != _underlineStyleModifier) {
_underlineStyleModifier = modifier;
[self.mutableAttributedString setUnderlineStyle:self.underlineStyle modifier:modifier];
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setUnderlineStyle:(CTUnderlineStyle)style modifier:(CTUnderlineStyleModifiers)modifier range:(NSRange)range {
[self.mutableAttributedString setUnderlineStyle:style modifier:modifier range:range];
[self attributedTextDidChange];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setStrokeWidth:(CGFloat)strokeWidth {
if (_strokeWidth != strokeWidth) {
_strokeWidth = strokeWidth;
[self.mutableAttributedString setStrokeWidth:strokeWidth];
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setStrokeWidth:(CGFloat)width range:(NSRange)range {
[self.mutableAttributedString setStrokeWidth:width range:range];
[self attributedTextDidChange];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setStrokeColor:(UIColor *)strokeColor {
if (_strokeColor != strokeColor) {
_strokeColor = strokeColor;
[self.mutableAttributedString setStrokeColor:_strokeColor];
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setStrokeColor:(UIColor*)color range:(NSRange)range {
[self.mutableAttributedString setStrokeColor:color range:range];
[self attributedTextDidChange];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTextKern:(CGFloat)textKern {
if (_textKern != textKern) {
_textKern = textKern;
[self.mutableAttributedString setKern:_textKern];
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTextKern:(CGFloat)kern range:(NSRange)range {
[self.mutableAttributedString setKern:kern range:range];
[self attributedTextDidChange];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setLinkColor:(UIColor *)linkColor {
if (_linkColor != linkColor) {
_linkColor = linkColor;
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setLineHeight:(CGFloat)lineHeight {
_lineHeight = lineHeight;
if (nil != self.mutableAttributedString) {
CTTextAlignment alignment = [self.class alignmentFromUITextAlignment:self.textAlignment];
CTLineBreakMode lineBreak = [self.class lineBreakModeFromUILineBreakMode:self.lineBreakMode];
[self.mutableAttributedString setTextAlignment:alignment lineBreakMode:lineBreak lineHeight:self.lineHeight];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setHighlightedLinkBackgroundColor:(UIColor *)highlightedLinkBackgroundColor {
if (_highlightedLinkBackgroundColor != highlightedLinkBackgroundColor) {
_highlightedLinkBackgroundColor = highlightedLinkBackgroundColor;
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setLinksHaveUnderlines:(BOOL)linksHaveUnderlines {
if (_linksHaveUnderlines != linksHaveUnderlines) {
_linksHaveUnderlines = linksHaveUnderlines;
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setAttributesForLinks:(NSDictionary *)attributesForLinks {
if (_attributesForLinks != attributesForLinks) {
_attributesForLinks = attributesForLinks;
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setAttributesForHighlightedLink:(NSDictionary *)attributesForHighlightedLink {
if (_attributesForHighlightedLink != attributesForHighlightedLink) {
_attributesForHighlightedLink = attributesForHighlightedLink;
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setExplicitLinkLocations:(NSMutableArray *)explicitLinkLocations {
if (_explicitLinkLocations != explicitLinkLocations) {
_explicitLinkLocations = explicitLinkLocations;
self.accessibleElements = nil;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setDetectedlinkLocations:(NSArray *)detectedlinkLocations{
if (_detectedlinkLocations != detectedlinkLocations) {
_detectedlinkLocations = detectedlinkLocations;
self.accessibleElements = nil;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setHighlighted:(BOOL)highlighted {
BOOL didChange = self.highlighted != highlighted;
[super setHighlighted:highlighted];
if (didChange) {
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setHighlightedTextColor:(UIColor *)highlightedTextColor {
BOOL didChange = self.highlightedTextColor != highlightedTextColor;
[super setHighlightedTextColor:highlightedTextColor];
if (didChange) {
[self attributedTextDidChange];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSArray *)_matchesFromAttributedString:(NSString *)string {
NSError* error = nil;
NSDataDetector* linkDetector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)self.dataDetectorTypes
error:&error];
NSRange range = NSMakeRange(0, string.length);
return [linkDetector matchesInString:string options:0 range:range];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)_deferLinkDetection {
if (!self.detectingLinks) {
self.detectingLinks = YES;
NSString* string = [self.mutableAttributedString.string copy];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray* matches = [self _matchesFromAttributedString:string];
self.detectingLinks = NO;
dispatch_async(dispatch_get_main_queue(), ^{
self.detectedlinkLocations = matches;
self.linksHaveBeenDetected = YES;
[self attributedTextDidChange];
});
});
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Use an NSDataDetector to find any implicit links in the text. The results are cached until
// the text changes.
- (void)detectLinks {
if (nil == self.mutableAttributedString) {
return;
}
if (self.autoDetectLinks && !self.linksHaveBeenDetected) {
if (self.deferLinkDetection) {
[self _deferLinkDetection];
} else {
self.detectedlinkLocations = [self _matchesFromAttributedString:self.mutableAttributedString.string];
self.linksHaveBeenDetected = YES;
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGRect)getLineBounds:(CTLineRef)line point:(CGPoint) point {
CGFloat ascent = 0.0f;
CGFloat descent = 0.0f;
CGFloat leading = 0.0f;
CGFloat width = (CGFloat)CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
CGFloat height = ascent + descent;
return CGRectMake(point.x, point.y - descent, width, height);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSTextCheckingResult *)linkAtIndex:(CFIndex)i {
NSTextCheckingResult* foundResult = nil;
if (self.autoDetectLinks) {
[self detectLinks];
for (NSTextCheckingResult* result in self.detectedlinkLocations) {
if (NSLocationInRange(i, result.range)) {
foundResult = result;
break;
}
}
}
if (nil == foundResult) {
for (NSTextCheckingResult* result in self.explicitLinkLocations) {
if (NSLocationInRange(i, result.range)) {
foundResult = result;
break;
}
}
}
return foundResult;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)_processLinksInAttributedString:(NSAttributedString *)attributedString {
// Pull any attributes matching the link attribute from the attributed string and store them as
// the current set of explicit links. This properly handles the value of the attribute being
// either an NSURL or an NSString.
__block NSMutableArray *links = [NSMutableArray array];
[attributedString enumerateAttribute:kNILinkAttributeName
inRange:NSMakeRange(0, attributedString.length)
options:0
usingBlock:^(id value, NSRange range, BOOL *stop) {
if (value != nil)
{
if ([value isKindOfClass:[NSURL class]])
{
[links addObject:[NSTextCheckingResult linkCheckingResultWithRange:range URL:value]];
}
else if ([value isKindOfClass:[NSString class]])
{
NSURL *url = [NSURL URLWithString:value];
[links addObject:[NSTextCheckingResult linkCheckingResultWithRange:range URL:url]];
}
}
}];
self.explicitLinkLocations = links;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)_verticalOffsetForBounds:(CGRect)bounds {
CGFloat verticalOffset = 0;
if (NIVerticalTextAlignmentTop != self.verticalTextAlignment) {
// When the text is attached to the top we can easily just start drawing and leave the
// remainder. This is the most performant case.
// With other alignment modes we must calculate the size of the text first.
CGSize textSize = [self sizeThatFits:CGSizeMake(bounds.size.width, CGFLOAT_MAX)];
if (NIVerticalTextAlignmentMiddle == self.verticalTextAlignment) {
verticalOffset = floorf((bounds.size.height - textSize.height) / 2.f);
} else if (NIVerticalTextAlignmentBottom == self.verticalTextAlignment) {
verticalOffset = bounds.size.height - textSize.height;
}
}
return verticalOffset;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGAffineTransform)_transformForCoreText {
// CoreText context coordinates are the opposite to UIKit so we flip the bounds
return CGAffineTransformScale(CGAffineTransformMakeTranslation(0, self.bounds.size.height), 1.f, -1.f);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSTextCheckingResult *)linkAtPoint:(CGPoint)point {
if (!CGRectContainsPoint(CGRectInset(self.bounds, 0, -kVMargin), point)) {
return nil;
}
CFArrayRef lines = CTFrameGetLines(self.textFrame);
if (!lines) return nil;
CFIndex count = CFArrayGetCount(lines);
NSTextCheckingResult* foundLink = nil;
CGPoint origins[count];
CTFrameGetLineOrigins(self.textFrame, CFRangeMake(0,0), origins);
CGAffineTransform transform = [self _transformForCoreText];
CGFloat verticalOffset = [self _verticalOffsetForBounds:self.bounds];
for (int i = 0; i < count; i++) {
CGPoint linePoint = origins[i];
CTLineRef line = CFArrayGetValueAtIndex(lines, i);
CGRect flippedRect = [self getLineBounds:line point:linePoint];
CGRect rect = CGRectApplyAffineTransform(flippedRect, transform);
rect = CGRectInset(rect, 0, -kVMargin);
rect = CGRectOffset(rect, 0, verticalOffset);
if (CGRectContainsPoint(rect, point)) {
CGPoint relativePoint = CGPointMake(point.x-CGRectGetMinX(rect),
point.y-CGRectGetMinY(rect));
CFIndex idx = CTLineGetStringIndexForPosition(line, relativePoint);
NSUInteger offset = 0;
for (NIAttributedLabelImage *labelImage in self.images) {
if (labelImage.index < idx) {
offset++;
}
}
foundLink = [self linkAtIndex:idx - offset];;
if (foundLink) {
NSTextCheckingResult *result = [NSTextCheckingResult linkCheckingResultWithRange:NSMakeRange(foundLink.range.location + offset, foundLink.range.length) URL:foundLink.URL];
return result;
}
}
}
return nil;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGRect)_rectForRange:(NSRange)range inLine:(CTLineRef)line lineOrigin:(CGPoint)lineOrigin {
CGRect rectForRange = CGRectZero;
CFArrayRef runs = CTLineGetGlyphRuns(line);
CFIndex runCount = CFArrayGetCount(runs);
// Iterate through each of the "runs" (i.e. a chunk of text) and find the runs that
// intersect with the range.
for (CFIndex k = 0; k < runCount; k++) {
CTRunRef run = CFArrayGetValueAtIndex(runs, k);
CFRange stringRunRange = CTRunGetStringRange(run);
NSRange lineRunRange = NSMakeRange(stringRunRange.location, stringRunRange.length);
NSRange intersectedRunRange = NSIntersectionRange(lineRunRange, range);
if (intersectedRunRange.length == 0) {
// This run doesn't intersect the range, so skip it.
continue;
}
CGFloat ascent = 0.0f;
CGFloat descent = 0.0f;
CGFloat leading = 0.0f;
// Use of 'leading' doesn't properly highlight Japanese-character link.
CGFloat width = (CGFloat)CTRunGetTypographicBounds(run,
CFRangeMake(0, 0),
&ascent,
&descent,
NULL); //&leading);
CGFloat height = ascent + descent;
CGFloat xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, nil);
CGRect linkRect = CGRectMake(lineOrigin.x + xOffset - leading, lineOrigin.y - descent, width + leading, height);
linkRect.origin.y = roundf(linkRect.origin.y);
linkRect.origin.x = roundf(linkRect.origin.x);
linkRect.size.width = roundf(linkRect.size.width);
linkRect.size.height = roundf(linkRect.size.height);
if (CGRectIsEmpty(rectForRange)) {
rectForRange = linkRect;
} else {
rectForRange = CGRectUnion(rectForRange, linkRect);
}
}
return rectForRange;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)isPoint:(CGPoint)point nearLink:(NSTextCheckingResult *)link {
CFArrayRef lines = CTFrameGetLines(self.textFrame);
if (nil == lines) {
return NO;
}
CFIndex count = CFArrayGetCount(lines);
CGPoint lineOrigins[count];
CTFrameGetLineOrigins(self.textFrame, CFRangeMake(0, 0), lineOrigins);
CGAffineTransform transform = [self _transformForCoreText];
CGFloat verticalOffset = [self _verticalOffsetForBounds:self.bounds];
NSRange linkRange = link.range;
BOOL isNearLink = NO;
for (int i = 0; i < count; i++) {
CTLineRef line = CFArrayGetValueAtIndex(lines, i);
CGRect linkRect = [self _rectForRange:linkRange inLine:line lineOrigin:lineOrigins[i]];
if (!CGRectIsEmpty(linkRect)) {
linkRect = CGRectApplyAffineTransform(linkRect, transform);
linkRect = CGRectOffset(linkRect, 0, verticalOffset);
linkRect = CGRectInset(linkRect, -kTouchGutter, -kTouchGutter);
if (CGRectContainsPoint(linkRect, point)) {
isNearLink = YES;
break;
}
}
}
return isNearLink;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSArray *)_rectsForLink:(NSTextCheckingResult *)link {
CFArrayRef lines = CTFrameGetLines(self.textFrame);
if (nil == lines) {
return nil;
}
CFIndex count = CFArrayGetCount(lines);
CGPoint lineOrigins[count];
CTFrameGetLineOrigins(self.textFrame, CFRangeMake(0, 0), lineOrigins);
CGAffineTransform transform = [self _transformForCoreText];
CGFloat verticalOffset = [self _verticalOffsetForBounds:self.bounds];
NSRange linkRange = link.range;
NSMutableArray* rects = [NSMutableArray array];
for (int i = 0; i < count; i++) {
CTLineRef line = CFArrayGetValueAtIndex(lines, i);
CGRect linkRect = [self _rectForRange:linkRange inLine:line lineOrigin:lineOrigins[i]];
if (!CGRectIsEmpty(linkRect)) {
linkRect = CGRectApplyAffineTransform(linkRect, transform);
linkRect = CGRectOffset(linkRect, 0, verticalOffset);
[rects addObject:[NSValue valueWithCGRect:linkRect]];
}
}
return [rects copy];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTouchedLink:(NSTextCheckingResult *)touchedLink {
if (_touchedLink != touchedLink) {
_touchedLink = touchedLink;
if (self.attributesForHighlightedLink.count > 0) {
[self attributedTextDidChange];
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
UITouch* touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
self.touchedLink = [self linkAtPoint:point];
self.touchPoint = point;
self.originalLink = self.touchedLink;
[self.longPressTimer invalidate];
if (nil != self.touchedLink) {
self.longPressTimer = [NSTimer scheduledTimerWithTimeInterval:kLongPressTimeInterval target:self selector:@selector(_longPressTimerDidFire:) userInfo:nil repeats:NO];
}
[self setNeedsDisplay];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];