-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathNIAttributedLabel.m
More file actions
1608 lines (1260 loc) · 56.6 KB
/
NIAttributedLabel.m
File metadata and controls
1608 lines (1260 loc) · 56.6 KB
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 (c) 2011-present, NimbusKit. All rights reserved.
Originally created by Roger Chapman
This source code is licensed under the BSD-style license found in the LICENSE file in the root
directory of this source tree and at the http://nimbuskit.info/license url. An additional grant of
patent rights can be found in the PATENTS file in the same directory and url.
*/
#import "NIAttributedLabel.h"
#import "NSMutableAttributedString+NimbusKitAttributedLabel.h"
#import "NimbusKitBasics.h"
#import <QuartzCore/QuartzCore.h>
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "NimbusKit requires ARC support."
#endif
#if __IPHONE_OS_VERSION_MIN_REQUIRED < NI_IOS_6_0
#error "NIAttributedLabel requires iOS 6 or higher."
#endif
// The number of seconds to wait before executing a long press action on the tapped link.
static const NSTimeInterval kLongPressTimeInterval = 0.5;
// The number of pixels the user's finger must move before cancelling the long press timer.
static const CGFloat kLongPressGutter = 22;
// 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;
static const CGFloat kVMargin = 5.0f;
// \u2026 is the Unicode horizontal ellipsis character code
static NSString* const kEllipsesCharacter = @"\u2026";
NSString* const NIAttributedLabelLinkAttributeName = @"NIAttributedLabel:Link";
// For supporting images.
CGFloat NIImageDelegateGetAscentCallback(void* refCon);
CGFloat NIImageDelegateGetDescentCallback(void* refCon);
CGFloat NIImageDelegateGetWidthCallback(void* refCon);
CGSize NISizeOfAttributedStringConstrainedToSize(NSAttributedString* attributedString, CGSize constraintSize, 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 == 1) {
constraintSize = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX);
} else if (numberOfLines > 0 && nil != framesetter) {
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0, 0, constraintSize.width, constraintSize.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);
}
CGSize newSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, range, NULL, constraintSize, NULL);
if (nil != framesetter) {
CFRelease(framesetter);
framesetter = nil;
}
return CGSizeMake(ceil(newSize.width), ceil(newSize.height));
}
@interface NIAttributedLabelImage : NSObject
- (CGSize)boxSize; // imageSize + margins
@property (nonatomic) NSInteger index;
@property (nonatomic, strong) UIImage* image;
@property (nonatomic) UIEdgeInsets margins;
@property (nonatomic) NIVerticalTextAlignment verticalTextAlignment;
@property (nonatomic) CGFloat fontAscent;
@property (nonatomic) CGFloat fontDescent;
@end
@implementation NIAttributedLabelImage
- (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, strong) NSMutableAttributedString* mutableAttributedString;
@property (nonatomic) CTFrameRef textFrame; // CFType, manually managed lifetime, see setter.
@property (assign) BOOL detectingLinks; // Atomic.
@property (nonatomic) BOOL linksHaveBeenDetected;
@property (nonatomic, copy) NSArray* detectedlinkLocations;
@property (nonatomic, strong) NSMutableArray* explicitLinkLocations;
@property (nonatomic, strong) NSTextCheckingResult* originalLink;
@property (nonatomic, strong) NSTextCheckingResult* touchedLink;
@property (nonatomic, strong) NSTimer* longPressTimer;
@property (nonatomic) CGPoint touchPoint;
@property (nonatomic, strong) NSTextCheckingResult* actionSheetLink;
@property (nonatomic, copy) NSArray* accessibleElements;
@property (nonatomic, strong) NSMutableArray *images;
@end
@interface NIAttributedLabel (ConversionUtilities)
+ (CTTextAlignment)alignmentFromUITextAlignment:(NSTextAlignment)alignment;
+ (CTLineBreakMode)lineBreakModeFromUILineBreakMode:(NSLineBreakMode)lineBreakMode;
+ (NSMutableAttributedString *)mutableAttributedStringFromLabel:(UILabel *)label;
@end
@implementation NIAttributedLabel
@synthesize textFrame = _textFrame;
- (void)dealloc {
[_longPressTimer invalidate];
// The property is marked 'assign', but retain count for this CFType is managed here and via
// the setter.
if (NULL != _textFrame) {
CFRelease(_textFrame);
}
}
- (CTFrameRef)textFrame {
if (NULL == _textFrame) {
NSMutableAttributedString* attributedStringWithLinks = [self mutableAttributedStringWithAdditions];
CFAttributedStringRef attributedString = (__bridge CFAttributedStringRef)attributedStringWithLinks;
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attributedString);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, self.bounds);
CTFrameRef textFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
self.textFrame = textFrame;
if (textFrame) {
CFRelease(textFrame);
}
CGPathRelease(path);
CFRelease(framesetter);
}
return _textFrame;
}
- (void)setTextFrame:(CTFrameRef)textFrame {
// The property is marked 'assign', but retain count for this CFType is managed via this setter
// and -dealloc.
if (textFrame != _textFrame) {
if (NULL != _textFrame) {
CFRelease(_textFrame);
}
if (NULL != textFrame) {
CFRetain(textFrame);
}
_textFrame = textFrame;
}
}
- (void)_configureDefaults {
self.verticalTextAlignment = NIVerticalTextAlignmentTop;
self.linkColor = NITintColorForViewWithFallback(self, [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];
self.attributedText = [[self class] mutableAttributedStringFromLabel:self];
}
- (void)resetTextFrame {
self.textFrame = NULL;
self.accessibleElements = nil;
}
- (void)attributedTextDidChange {
[self resetTextFrame];
[self invalidateIntrinsicContentSize];
[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);
}
- (CGSize)intrinsicContentSize {
return [self sizeThatFits:[super intrinsicContentSize]];
}
#pragma mark - Public
- (void)setText:(NSString *)text {
[super setText:text];
self.attributedText = [[self class] mutableAttributedStringFromLabel:self];
// Apply NIAttributedLabel-specific styles.
[self.mutableAttributedString nimbuskit_setUnderlineStyle:_underlineStyle modifier:_underlineStyleModifier];
[self.mutableAttributedString nimbuskit_setStrokeWidth:_strokeWidth];
[self.mutableAttributedString nimbuskit_setStrokeColor:_strokeColor];
[self.mutableAttributedString nimbuskit_setKern:_textKern];
}
- (NSAttributedString *)attributedText {
return [self.mutableAttributedString copy];
}
- (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];
}
}
- (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];
}
- (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 nimbuskit_setTextAlignment:alignment lineBreakMode:lineBreak lineHeight:self.lineHeight];
}
}
- (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 nimbuskit_setTextAlignment:alignment lineBreakMode:lineBreak lineHeight:self.lineHeight];
}
}
- (void)setTextColor:(UIColor *)textColor {
[super setTextColor:textColor];
[self.mutableAttributedString nimbuskit_setTextColor:textColor];
[self attributedTextDidChange];
}
- (void)setTextColor:(UIColor *)textColor range:(NSRange)range {
[self.mutableAttributedString nimbuskit_setTextColor:textColor range:range];
[self attributedTextDidChange];
}
- (void)setFont:(UIFont *)font {
[super setFont:font];
[self.mutableAttributedString nimbuskit_setFont:font];
[self attributedTextDidChange];
}
- (void)setFont:(UIFont *)font range:(NSRange)range {
[self.mutableAttributedString nimbuskit_setFont:font range:range];
[self attributedTextDidChange];
}
- (void)setUnderlineStyle:(CTUnderlineStyle)style {
if (style != _underlineStyle) {
_underlineStyle = style;
[self.mutableAttributedString nimbuskit_setUnderlineStyle:style modifier:self.underlineStyleModifier];
[self attributedTextDidChange];
}
}
- (void)setUnderlineStyleModifier:(CTUnderlineStyleModifiers)modifier {
if (modifier != _underlineStyleModifier) {
_underlineStyleModifier = modifier;
[self.mutableAttributedString nimbuskit_setUnderlineStyle:self.underlineStyle modifier:modifier];
[self attributedTextDidChange];
}
}
- (void)setUnderlineStyle:(CTUnderlineStyle)style modifier:(CTUnderlineStyleModifiers)modifier range:(NSRange)range {
[self.mutableAttributedString nimbuskit_setUnderlineStyle:style modifier:modifier range:range];
[self attributedTextDidChange];
}
- (void)setShadowBlur:(CGFloat)shadowBlur {
if (_shadowBlur != shadowBlur) {
_shadowBlur = shadowBlur;
[self attributedTextDidChange];
}
}
- (void)setStrokeWidth:(CGFloat)strokeWidth {
if (_strokeWidth != strokeWidth) {
_strokeWidth = strokeWidth;
[self.mutableAttributedString nimbuskit_setStrokeWidth:strokeWidth];
[self attributedTextDidChange];
}
}
- (void)setStrokeWidth:(CGFloat)width range:(NSRange)range {
[self.mutableAttributedString nimbuskit_setStrokeWidth:width range:range];
[self attributedTextDidChange];
}
- (void)setStrokeColor:(UIColor *)strokeColor {
if (_strokeColor != strokeColor) {
_strokeColor = strokeColor;
[self.mutableAttributedString nimbuskit_setStrokeColor:_strokeColor];
[self attributedTextDidChange];
}
}
- (void)setStrokeColor:(UIColor*)color range:(NSRange)range {
[self.mutableAttributedString nimbuskit_setStrokeColor:color range:range];
[self attributedTextDidChange];
}
- (void)setTextKern:(CGFloat)textKern {
if (_textKern != textKern) {
_textKern = textKern;
[self.mutableAttributedString nimbuskit_setKern:_textKern];
[self attributedTextDidChange];
}
}
- (void)setTextKern:(CGFloat)kern range:(NSRange)range {
[self.mutableAttributedString nimbuskit_setKern:kern range:range];
[self attributedTextDidChange];
}
- (void)setTailTruncationString:(NSString *)tailTruncationString {
if (![_tailTruncationString isEqualToString:tailTruncationString]) {
_tailTruncationString = [tailTruncationString copy];
[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 nimbuskit_setTextAlignment:alignment lineBreakMode:lineBreak lineHeight:self.lineHeight];
[self attributedTextDidChange];
}
}
- (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.
__block NSMutableArray *links = [NSMutableArray array];
[attributedString enumerateAttribute:NIAttributedLabelLinkAttributeName
inRange:NSMakeRange(0, attributedString.length)
options:0
usingBlock:^(id value, NSRange range, BOOL *stop) {
if (value != nil) {
[links addObject:value];
}
}];
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 = floor((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);
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++;
}
}
NSTextCheckingResult* foundLink = [self linkAtIndex:idx - offset];
if (foundLink) {
return foundLink;
}
}
}
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 = round(linkRect.origin.y);
linkRect.origin.x = round(linkRect.origin.x);
linkRect.size.width = round(linkRect.size.width);
linkRect.size.height = round(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 {
UITouch* touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
self.touchedLink = [self linkAtPoint:point];
self.touchPoint = point;
self.originalLink = self.touchedLink;
if (self.originalLink) {
[self.longPressTimer invalidate];
if (nil != self.touchedLink) {
self.longPressTimer = [NSTimer scheduledTimerWithTimeInterval:kLongPressTimeInterval target:self selector:@selector(_longPressTimerDidFire:) userInfo:nil repeats:NO];
}
} else {
[super touchesBegan:touches withEvent:event];
}
[self setNeedsDisplay];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch* touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
if (self.originalLink) {
// If the user moves their finger away from the original link, deselect it.
// If the user moves their finger back to the original link, reselect it.
// Don't allow other links to be selected other than the original link.
if (nil != self.originalLink) {
NSTextCheckingResult* oldTouchedLink = self.touchedLink;
if ([self isPoint:point nearLink:self.originalLink]) {
self.touchedLink = self.originalLink;
} else {
self.touchedLink = nil;
}
if (oldTouchedLink != self.touchedLink) {
[self.longPressTimer invalidate];
self.longPressTimer = nil;
[self setNeedsDisplay];
}
}
// If the user moves their finger within the link beyond a certain gutter amount, reset the
// hold timer. The user must hold their finger still for the long press interval in order for
// the long press action to fire.
if ((self.linkShortTouch && self.touchPoint.x - point.x >= 0 ) ||
(self.linkShortTouch && self.touchPoint.y - point.y >= 0 )){
if (nil != self.touchedLink && nil != self.originalLink) {
[[UIApplication sharedApplication] openURL:self.originalLink.URL options:@{} completionHandler:nil];
}
}else if (fabs(self.touchPoint.x - point.x) >= kLongPressGutter
|| fabs(self.touchPoint.y - point.y) >= kLongPressGutter) {
if (nil != self.touchedLink) {
self.touchPoint = point;
}
}
} else {
[super touchesMoved:touches withEvent:event];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if (self.originalLink) {
[self.longPressTimer invalidate];
self.longPressTimer = nil;
UITouch* touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
if (nil != self.originalLink) {
if ([self isPoint:point nearLink:self.originalLink]
&& [self.delegate respondsToSelector:@selector(attributedLabel:didSelectTextCheckingResult:atPoint:)]) {
[self.delegate attributedLabel:self didSelectTextCheckingResult:self.originalLink atPoint:point];
}
}
self.touchedLink = nil;
self.originalLink = nil;
[self setNeedsDisplay];
} else {
[super touchesEnded:touches withEvent:event];
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesCancelled:touches withEvent:event];
[self.longPressTimer invalidate];
self.longPressTimer = nil;
self.touchedLink = nil;
self.originalLink = nil;
[self setNeedsDisplay];
}
- (UIActionSheet *)actionSheetForResult:(NSTextCheckingResult *)result {
UIActionSheet* actionSheet =
[[UIActionSheet alloc] initWithTitle:nil
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
NSString* title = nil;
if (NSTextCheckingTypeLink == result.resultType) {
if ([result.URL.scheme isEqualToString:@"mailto"]) {
title = result.URL.resourceSpecifier;
[actionSheet addButtonWithTitle:NSLocalizedString(@"Open in Mail", @"")];
[actionSheet addButtonWithTitle:NSLocalizedString(@"Copy Email Address", @"")];
} else {
title = result.URL.absoluteString;
[actionSheet addButtonWithTitle:NSLocalizedString(@"Open in Safari", @"")];
[actionSheet addButtonWithTitle:NSLocalizedString(@"Copy URL", @"")];
}
} else if (NSTextCheckingTypePhoneNumber == result.resultType) {
title = result.phoneNumber;
[actionSheet addButtonWithTitle:NSLocalizedString(@"Call", @"")];
[actionSheet addButtonWithTitle:NSLocalizedString(@"Copy Phone Number", @"")];
} else if (NSTextCheckingTypeAddress == result.resultType) {
title = [self.mutableAttributedString.string substringWithRange:self.actionSheetLink.range];
[actionSheet addButtonWithTitle:NSLocalizedString(@"Open in Maps", @"")];
[actionSheet addButtonWithTitle:NSLocalizedString(@"Copy Address", @"")];
} else {
// This type has not been implemented yet.
NI_DASSERT(NO);
[actionSheet addButtonWithTitle:NSLocalizedString(@"Copy", @"")];
}
actionSheet.title = title;
if (!NIIsPad()) {
[actionSheet setCancelButtonIndex:[actionSheet addButtonWithTitle:NSLocalizedString(@"Cancel", @"")]];
}
return actionSheet;
}
- (void)_longPressTimerDidFire:(NSTimer *)timer {
self.longPressTimer = nil;
if (nil != self.touchedLink) {
self.actionSheetLink = self.touchedLink;
UIActionSheet* actionSheet = [self actionSheetForResult:self.actionSheetLink];
BOOL shouldPresent = YES;
if ([self.delegate respondsToSelector:@selector(attributedLabel:shouldPresentActionSheet:withTextCheckingResult:atPoint:)]) {
// Give the delegate the opportunity to not show the action sheet or to present its own.
shouldPresent = [self.delegate attributedLabel:self shouldPresentActionSheet:actionSheet withTextCheckingResult:self.touchedLink atPoint:self.touchPoint];
}
if (shouldPresent) {
if (NIIsPad()) {
[actionSheet showFromRect:CGRectMake(self.touchPoint.x - 22, self.touchPoint.y - 22, 44, 44) inView:self animated:YES];
} else {
[actionSheet showInView:self];
}
} else {
self.actionSheetLink = nil;
}
}
}
- (void)_applyLinkStyleWithResults:(NSArray *)results toAttributedString:(NSMutableAttributedString *)attributedString {