forked from AliSoftware/OHAttributedLabel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOHAttributedLabel.m
864 lines (732 loc) · 28.1 KB
/
OHAttributedLabel.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
/***********************************************************************************
*
* Copyright (c) 2010 Olivier Halligon
*
* 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.
*
***********************************************************************************
*
* Created by Olivier Halligon (AliSoftware) on 20 Jul. 2010.
*
* Any comment or suggestion welcome. Please contact me before using this class in
* your projects. Referencing this project in your AboutBox/Credits is appreciated.
*
***********************************************************************************/
#import "OHAttributedLabel.h"
#import "NSAttributedString+Attributes.h"
#define OHAttributedLabel_WarnAboutKnownIssues 1
/////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Private Utility methods
CGPoint CGPointFlipped(CGPoint point, CGRect bounds);
CGRect CGRectFlipped(CGRect rect, CGRect bounds);
NSRange NSRangeFromCFRange(CFRange range);
CGRect CTLineGetTypographicBoundsAsRect(CTLineRef line, CGPoint lineOrigin);
CGRect CTRunGetTypographicBoundsAsRect(CTRunRef run, CTLineRef line, CGPoint lineOrigin);
BOOL CTLineContainsCharactersFromStringRange(CTLineRef line, NSRange range);
BOOL CTRunContainsCharactersFromStringRange(CTRunRef run, NSRange range);
/////////////////////////////////////////////////////////////////////////////////////
CTTextAlignment CTTextAlignmentFromUITextAlignment(UITextAlignment alignment)
{
if (alignment == (UITextAlignment)kCTJustifiedTextAlignment)
{
/* special OOB value, so test it outside of the switch to avoid warning */
return kCTJustifiedTextAlignment;
}
switch (alignment)
{
case UITextAlignmentLeft: return kCTLeftTextAlignment;
case UITextAlignmentCenter: return kCTCenterTextAlignment;
case UITextAlignmentRight: return kCTRightTextAlignment;
default: return kCTNaturalTextAlignment;
}
}
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;
}
}
// Don't use this method for origins. Origins always depend on the height of the rect.
CGPoint CGPointFlipped(CGPoint point, CGRect bounds)
{
return CGPointMake(point.x, CGRectGetMaxY(bounds)-point.y);
}
CGRect CGRectFlipped(CGRect rect, CGRect bounds)
{
return CGRectMake(CGRectGetMinX(rect),
CGRectGetMaxY(bounds)-CGRectGetMaxY(rect),
CGRectGetWidth(rect),
CGRectGetHeight(rect));
}
NSRange NSRangeFromCFRange(CFRange range)
{
return NSMakeRange(range.location, range.length);
}
// Font Metrics: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/FontHandling/Tasks/GettingFontMetrics.html
CGRect CTLineGetTypographicBoundsAsRect(CTLineRef line, CGPoint lineOrigin)
{
CGFloat ascent = 0;
CGFloat descent = 0;
CGFloat leading = 0;
CGFloat width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
CGFloat height = ascent + descent;
return CGRectMake(lineOrigin.x,
lineOrigin.y - descent,
width,
height);
}
CGRect CTRunGetTypographicBoundsAsRect(CTRunRef run, CTLineRef line, CGPoint lineOrigin)
{
CGFloat ascent = 0;
CGFloat descent = 0;
CGFloat leading = 0;
CGFloat width = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, &leading);
CGFloat height = ascent + descent;
CGFloat xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, NULL);
return CGRectMake(lineOrigin.x + xOffset,
lineOrigin.y - descent,
width,
height);
}
BOOL CTLineContainsCharactersFromStringRange(CTLineRef line, NSRange range)
{
NSRange lineRange = NSRangeFromCFRange(CTLineGetStringRange(line));
NSRange intersectedRange = NSIntersectionRange(lineRange, range);
return (intersectedRange.length > 0);
}
BOOL CTRunContainsCharactersFromStringRange(CTRunRef run, NSRange range)
{
NSRange runRange = NSRangeFromCFRange(CTRunGetStringRange(run));
NSRange intersectedRange = NSIntersectionRange(runRange, range);
return (intersectedRange.length > 0);
}
@implementation NSTextCheckingResult(Extended)
-(NSURL*)extendedURL
{
NSURL* url = self.URL;
if (self.resultType == NSTextCheckingTypeAddress)
{
NSString* baseURL = ([UIDevice currentDevice].systemVersion.floatValue >= 6.0) ? @"maps.apple.com" : @"maps.google.com";
NSString* mapURLString = [NSString stringWithFormat:@"http://%@/maps?q=%@", baseURL,
[self.addressComponents.allValues componentsJoinedByString:@","]];
url = [NSURL URLWithString:mapURLString];
}
else if (self.resultType == NSTextCheckingTypePhoneNumber)
{
url = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", [self.phoneNumber stringByReplacingOccurrencesOfString:@" " withString:@""]]];
}
return url;
}
@end
/////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Private interface
const int UITextAlignmentJustify = ((UITextAlignment)kCTJustifiedTextAlignment);
@interface OHAttributedLabel(/* Private */)
{
NSAttributedString* _attributedText;
NSAttributedString* _attributedTextWithLinks;
CTFrameRef textFrame;
CGRect drawingRect;
NSMutableArray* _customLinks;
CGPoint _touchStartPoint;
}
@property(nonatomic, retain) NSTextCheckingResult* activeLink;
-(NSTextCheckingResult*)linkAtCharacterIndex:(CFIndex)idx;
-(NSTextCheckingResult*)linkAtPoint:(CGPoint)pt;
-(void)resetTextFrame;
-(void)drawActiveLinkHighlightForRect:(CGRect)rect;
#if OHAttributedLabel_WarnAboutKnownIssues
-(void)warnAboutKnownIssues_CheckLineBreakMode;
-(void)warnAboutKnownIssues_CheckAdjustsFontSizeToFitWidth;
#endif
@end
/////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Implementation
@implementation OHAttributedLabel
/////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Init/Dealloc
/////////////////////////////////////////////////////////////////////////////////////
- (void)commonInit
{
self.linkColor = [UIColor blueColor];
self.highlightedLinkColor = [UIColor colorWithWhite:0.4 alpha:0.3];
self.underlineLinks = YES;
self.automaticallyAddLinksForType = NSTextCheckingTypeLink;
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"tel:0"]]) {
self.automaticallyAddLinksForType |= NSTextCheckingTypePhoneNumber;
}
self.onlyCatchTouchesOnLinks = YES;
self.userInteractionEnabled = YES;
self.contentMode = UIViewContentModeRedraw;
[self resetAttributedText];
}
- (id) initWithFrame:(CGRect)aFrame
{
self = [super initWithFrame:aFrame];
if (self != nil)
{
[self commonInit];
}
return self;
}
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super initWithCoder:decoder];
if (self != nil)
{
[self commonInit];
#if OHAttributedLabel_WarnAboutKnownIssues
[self warnAboutKnownIssues_CheckLineBreakMode];
[self warnAboutKnownIssues_CheckAdjustsFontSizeToFitWidth];
#endif
}
return self;
}
-(void)dealloc
{
[self resetTextFrame]; // CFRelease the text frame
#if ! __has_feature(objc_arc)
[_linkColor release]; _linkColor = nil;
[_highlightedLinkColor release]; _highlightedLinkColor = nil;
[_activeLink release]; _activeLink = nil;
[_attributedText release]; _attributedText = nil;
[_attributedTextWithLinks release]; _attributedTextWithLinks = nil;
[_customLinks release]; _customLinks = nil;
[super dealloc];
#endif
}
/////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Links Managment
/////////////////////////////////////////////////////////////////////////////////////
-(void)addCustomLink:(NSURL*)linkUrl inRange:(NSRange)range
{
NSTextCheckingResult* link = [NSTextCheckingResult linkCheckingResultWithRange:range URL:linkUrl];
if (_customLinks == nil) {
_customLinks = [[NSMutableArray alloc] init];
}
[_customLinks addObject:link];
[self recomputeLinksInText];
[self setNeedsDisplay];
}
-(void)removeAllCustomLinks
{
[_customLinks removeAllObjects];
[self setNeedsDisplay];
}
-(void)recomputeLinksInText
{
if (!_attributedText || (self.automaticallyAddLinksForType == 0 && _customLinks.count == 0))
{
#if ! __has_feature(objc_arc)
[_attributedTextWithLinks release];
_attributedTextWithLinks = [_attributedText retain];
#else
_attributedTextWithLinks = _attributedText;
#endif
return;
}
NSMutableAttributedString* mutAS = [_attributedText mutableCopy];
BOOL hasLinkColorSelector = [self.delegate respondsToSelector:@selector(colorForLink:underlineStyle:)];
NSString* plainText = [_attributedText string];
if (plainText && (self.automaticallyAddLinksForType > 0))
{
NSDataDetector* linkDetector = [NSDataDetector dataDetectorWithTypes:self.automaticallyAddLinksForType error:nil];
[linkDetector enumerateMatchesInString:plainText options:0 range:NSMakeRange(0,[plainText length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{
int32_t uStyle = self.underlineLinks ? kCTUnderlineStyleSingle : kCTUnderlineStyleNone;
UIColor* thisLinkColor = hasLinkColorSelector ? [self.delegate colorForLink:result underlineStyle:&uStyle] : self.linkColor;
if (thisLinkColor)
[mutAS setTextColor:thisLinkColor range:[result range]];
if (uStyle>0)
[mutAS setTextUnderlineStyle:uStyle range:[result range]];
}];
}
[_customLinks enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSTextCheckingResult* result = (NSTextCheckingResult*)obj;
int32_t uStyle = self.underlineLinks ? kCTUnderlineStyleSingle : kCTUnderlineStyleNone;
UIColor* thisLinkColor = hasLinkColorSelector ? [self.delegate colorForLink:result underlineStyle:&uStyle] : self.linkColor;
@try {
if (thisLinkColor)
[mutAS setTextColor:thisLinkColor range:[result range]];
if (uStyle>0)
[mutAS setTextUnderlineStyle:uStyle range:[result range]];
}
@catch (NSException * e) {
// Protection against NSRangeException
if ([[e name] isEqualToString:NSRangeException]) {
NSLog(@"[OHAttributedLabel] exception: %@",e);
} else {
@throw;
}
}
}];
#if ! __has_feature(objc_arc)
[_attributedTextWithLinks release];
#endif
_attributedTextWithLinks = [[NSAttributedString alloc] initWithAttributedString:mutAS];
#if ! __has_feature(objc_arc)
[mutAS release];
#endif
[self setNeedsDisplay];
}
-(NSTextCheckingResult*)linkAtCharacterIndex:(CFIndex)idx
{
__block NSTextCheckingResult* foundResult = nil;
NSString* plainText = [_attributedText string];
if (plainText && (self.automaticallyAddLinksForType > 0))
{
NSError* error = nil;
NSDataDetector* linkDetector = [NSDataDetector dataDetectorWithTypes:self.automaticallyAddLinksForType error:&error];
[linkDetector enumerateMatchesInString:plainText options:0 range:NSMakeRange(0,[plainText length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{
NSRange r = [result range];
if (NSLocationInRange(idx, r))
{
#if __has_feature(objc_arc)
foundResult = result;
#else
foundResult = [[result retain] autorelease];
#endif
*stop = YES;
}
}];
}
if (!foundResult)
{
[_customLinks enumerateObjectsUsingBlock:^(id obj, NSUInteger aidx, BOOL *stop)
{
NSRange r = [(NSTextCheckingResult*)obj range];
if (NSLocationInRange(idx, r))
{
#if __has_feature(objc_arc)
foundResult = obj;
#else
foundResult = [[obj retain] autorelease];
#endif
*stop = YES;
}
}];
}
return foundResult;
}
-(NSTextCheckingResult*)linkAtPoint:(CGPoint)point
{
static const CGFloat kVMargin = 5.f;
if (!CGRectContainsPoint(CGRectInset(drawingRect, 0, -kVMargin), point)) return nil;
CFArrayRef lines = CTFrameGetLines(textFrame);
if (!lines) return nil;
CFIndex nbLines = CFArrayGetCount(lines);
NSTextCheckingResult* link = nil;
CGPoint origins[nbLines];
CTFrameGetLineOrigins(textFrame, CFRangeMake(0,0), origins);
for (int lineIndex=0 ; lineIndex<nbLines ; ++lineIndex) {
// this actually the origin of the line rect, so we need the whole rect to flip it
CGPoint lineOriginFlipped = origins[lineIndex];
CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex);
CGRect lineRectFlipped = CTLineGetTypographicBoundsAsRect(line, lineOriginFlipped);
CGRect lineRect = CGRectFlipped(lineRectFlipped, CGRectFlipped(drawingRect,self.bounds));
lineRect = CGRectInset(lineRect, 0, -kVMargin);
if (CGRectContainsPoint(lineRect, point)) {
CGPoint relativePoint = CGPointMake(point.x-CGRectGetMinX(lineRect),
point.y-CGRectGetMinY(lineRect));
CFIndex idx = CTLineGetStringIndexForPosition(line, relativePoint);
link = ([self linkAtCharacterIndex:idx]);
if (link) return link;
}
}
return nil;
}
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
// never return self. always return the result of [super hitTest..].
// this takes userInteraction state, enabled, alpha values etc. into account
UIView *hitResult = [super hitTest:point withEvent:event];
// don't check for links if the event was handled by one of the subviews
if (hitResult != self) {
return hitResult;
}
if (self.onlyCatchTouchesOnLinks) {
BOOL didHitLink = ([self linkAtPoint:point] != nil);
if (!didHitLink) {
// not catch the touch if it didn't hit a link
return nil;
}
}
return hitResult;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
CGPoint pt = [touch locationInView:self];
self.activeLink = [self linkAtPoint:pt];
_touchStartPoint = pt;
// we're using activeLink to draw a highlight in -drawRect:
[self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
CGPoint pt = [touch locationInView:self];
NSTextCheckingResult *linkAtTouchesEnded = [self linkAtPoint:pt];
BOOL closeToStart = (abs(_touchStartPoint.x - pt.x) < 10 && abs(_touchStartPoint.y - pt.y) < 10);
// we can check on equality of the ranges themselfes since the data detectors create new results
if (_activeLink && (NSEqualRanges(_activeLink.range,linkAtTouchesEnded.range) || closeToStart))
{
NSTextCheckingResult* linkToOpen = _activeLink;
#if ! __has_feature(objc_arc)
// In case the delegate calls recomputeLinksInText or anything that will clear the _activeLink variable, keep it around anyway
[[linkToOpen retain] autorelease];
#endif
BOOL openLink = (self.delegate && [self.delegate respondsToSelector:@selector(attributedLabel:shouldFollowLink:)])
? [self.delegate attributedLabel:self shouldFollowLink:linkToOpen] : YES;
if (openLink) [[UIApplication sharedApplication] openURL:linkToOpen.extendedURL];
}
self.activeLink = nil;
[self setNeedsDisplay];
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
self.activeLink = nil;
[self setNeedsDisplay];
}
/////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Drawing Text
/////////////////////////////////////////////////////////////////////////////////////
-(void)resetTextFrame
{
if (textFrame)
{
CFRelease(textFrame);
textFrame = NULL;
}
}
- (void)drawTextInRect:(CGRect)aRect
{
if (_attributedText)
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
// flipping the context to draw core text
// no need to flip our typographical bounds from now on
CGContextConcatCTM(ctx, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, self.bounds.size.height), 1.f, -1.f));
if (self.shadowColor)
{
CGContextSetShadowWithColor(ctx, self.shadowOffset, 0.0, self.shadowColor.CGColor);
}
NSAttributedString* attributedStringToDisplay = _attributedTextWithLinks;
if (self.highlighted && self.highlightedTextColor != nil)
{
NSMutableAttributedString* mutAS = [attributedStringToDisplay mutableCopy];
[mutAS setTextColor:self.highlightedTextColor];
attributedStringToDisplay = mutAS;
#if ! __has_feature(objc_arc)
[mutAS autorelease];
#endif
}
if (textFrame == NULL)
{
#if __has_feature(objc_arc)
CFAttributedStringRef cfAttrStrWithLinks = (__bridge CFAttributedStringRef)attributedStringToDisplay;
#else
CFAttributedStringRef cfAttrStrWithLinks = (CFAttributedStringRef)attributedStringToDisplay;
#endif
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(cfAttrStrWithLinks);
drawingRect = self.bounds;
if (self.centerVertically || self.extendBottomToFit)
{
CGSize sz = CTFramesetterSuggestFrameSizeWithConstraints(framesetter,CFRangeMake(0,0),NULL,CGSizeMake(drawingRect.size.width,CGFLOAT_MAX),NULL);
if (self.extendBottomToFit)
{
CGFloat delta = MAX(0.f , ceilf(sz.height - drawingRect.size.height)) + 10 /* Security margin */;
drawingRect.origin.y -= delta;
drawingRect.size.height += delta;
}
if (self.centerVertically) {
drawingRect.origin.y -= (drawingRect.size.height - sz.height)/2;
}
}
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, drawingRect);
textFrame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0,0), path, NULL);
CGPathRelease(path);
CFRelease(framesetter);
}
// draw highlights for activeLink
if (_activeLink)
{
[self drawActiveLinkHighlightForRect:drawingRect];
}
CTFrameDraw(textFrame, ctx);
CGContextRestoreGState(ctx);
} else {
[super drawTextInRect:aRect];
}
}
-(void)drawActiveLinkHighlightForRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextConcatCTM(ctx, CGAffineTransformMakeTranslation(rect.origin.x, rect.origin.y));
[self.highlightedLinkColor setFill];
NSRange activeLinkRange = _activeLink.range;
CFArrayRef lines = CTFrameGetLines(textFrame);
CFIndex lineCount = CFArrayGetCount(lines);
CGPoint lineOrigins[lineCount];
CTFrameGetLineOrigins(textFrame, CFRangeMake(0,0), lineOrigins);
for (CFIndex lineIndex = 0; lineIndex < lineCount; lineIndex++)
{
CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex);
if (!CTLineContainsCharactersFromStringRange(line, activeLinkRange))
{
continue; // with next line
}
// we use this rect to union the bounds of successive runs that belong to the same active link
CGRect unionRect = CGRectZero;
CFArrayRef runs = CTLineGetGlyphRuns(line);
CFIndex runCount = CFArrayGetCount(runs);
for (CFIndex runIndex = 0; runIndex < runCount; runIndex++)
{
CTRunRef run = CFArrayGetValueAtIndex(runs, runIndex);
if (!CTRunContainsCharactersFromStringRange(run, activeLinkRange))
{
if (!CGRectIsEmpty(unionRect))
{
CGContextFillRect(ctx, unionRect);
unionRect = CGRectZero;
}
continue; // with next run
}
CGRect linkRunRect = CTRunGetTypographicBoundsAsRect(run, line, lineOrigins[lineIndex]);
linkRunRect = CGRectIntegral(linkRunRect); // putting the rect on pixel edges
linkRunRect = CGRectInset(linkRunRect, -1, -1); // increase the rect a little
if (CGRectIsEmpty(unionRect))
{
unionRect = linkRunRect;
} else {
unionRect = CGRectUnion(unionRect, linkRunRect);
}
}
if (!CGRectIsEmpty(unionRect))
{
CGContextFillRect(ctx, unionRect);
//unionRect = CGRectZero;
}
}
CGContextRestoreGState(ctx);
}
- (CGSize)sizeThatFits:(CGSize)size
{
if (!_attributedTextWithLinks) return CGSizeZero;
return [_attributedTextWithLinks sizeConstrainedToSize:size fitRange:NULL];
}
/////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Setters/Getters
/////////////////////////////////////////////////////////////////////////////////////
@synthesize activeLink = _activeLink;
@synthesize linkColor = _linkColor;
@synthesize highlightedLinkColor = _highlightedLinkColor;
@synthesize underlineLinks = _underlineLinks;
@synthesize centerVertically = _centerVertically;
@synthesize automaticallyAddLinksForType = _automaticallyAddLinksForType;
@synthesize onlyCatchTouchesOnLinks = _onlyCatchTouchesOnLinks;
@synthesize extendBottomToFit = _extendBottomToFit;
@synthesize delegate = _delegate;
-(void)resetAttributedText
{
NSMutableAttributedString* mutAttrStr = [NSMutableAttributedString attributedStringWithString:self.text];
if (self.font) [mutAttrStr setFont:self.font];
if (self.textColor) [mutAttrStr setTextColor:self.textColor];
CTTextAlignment coreTextAlign = CTTextAlignmentFromUITextAlignment(self.textAlignment);
CTLineBreakMode coreTextLBMode = CTLineBreakModeFromUILineBreakMode(self.lineBreakMode);
[mutAttrStr setTextAlignment:coreTextAlign lineBreakMode:coreTextLBMode];
self.attributedText = [NSAttributedString attributedStringWithAttributedString:mutAttrStr];
}
-(NSAttributedString*)attributedText
{
if (!_attributedText)
{
[self resetAttributedText];
}
return _attributedText;
}
-(void)setAttributedText:(NSAttributedString*)newText
{
#if ! __has_feature(objc_arc)
[_attributedText release];
_attributedText = [newText retain];
#else
_attributedText = newText;
#endif
[self setAccessibilityLabel:_attributedText.string];
[self removeAllCustomLinks];
[self recomputeLinksInText];
}
/////////////////////////////////////////////////////////////////////////////////////
-(void)setText:(NSString *)text
{
NSString* cleanedText = [[text stringByReplacingOccurrencesOfString:@"\r\n" withString:@"\n"]
stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[super setText:cleanedText]; // will call setNeedsDisplay too
[self resetAttributedText];
}
-(void)setFont:(UIFont *)font
{
if (_attributedText)
{
NSMutableAttributedString* mutAS = [NSMutableAttributedString attributedStringWithAttributedString:_attributedText];
[mutAS setFont:font];
#if ! __has_feature(objc_arc)
[_attributedText release];
#endif
_attributedText = [[NSAttributedString alloc] initWithAttributedString:mutAS];
}
[super setFont:font]; // will call setNeedsDisplay too
}
-(void)setTextColor:(UIColor *)color
{
if (_attributedText)
{
NSMutableAttributedString* mutAS = [NSMutableAttributedString attributedStringWithAttributedString:_attributedText];
[mutAS setTextColor:color];
#if ! __has_feature(objc_arc)
[_attributedText release];
#endif
_attributedText = [[NSAttributedString alloc] initWithAttributedString:mutAS];
}
[super setTextColor:color]; // will call setNeedsDisplay too
}
-(void)setTextAlignment:(UITextAlignment)alignment
{
if (_attributedText)
{
CTTextAlignment coreTextAlign = CTTextAlignmentFromUITextAlignment(alignment);
CTLineBreakMode coreTextLBMode = CTLineBreakModeFromUILineBreakMode(self.lineBreakMode);
NSMutableAttributedString* mutAS = [NSMutableAttributedString attributedStringWithAttributedString:_attributedText];
[mutAS setTextAlignment:coreTextAlign lineBreakMode:coreTextLBMode];
#if ! __has_feature(objc_arc)
[_attributedText release];
#endif
_attributedText = [[NSAttributedString alloc] initWithAttributedString:mutAS];
}
[super setTextAlignment:alignment]; // will call setNeedsDisplay too
}
-(void)setLineBreakMode:(UILineBreakMode)lineBreakMode
{
if (_attributedText)
{
CTTextAlignment coreTextAlign = CTTextAlignmentFromUITextAlignment(self.textAlignment);
CTLineBreakMode coreTextLBMode = CTLineBreakModeFromUILineBreakMode(lineBreakMode);
NSMutableAttributedString* mutAS = [NSMutableAttributedString attributedStringWithAttributedString:_attributedText];
[mutAS setTextAlignment:coreTextAlign lineBreakMode:coreTextLBMode];
#if ! __has_feature(objc_arc)
[_attributedText release];
#endif
_attributedText = [[NSAttributedString alloc] initWithAttributedString:mutAS];
}
[super setLineBreakMode:lineBreakMode]; // will call setNeedsDisplay too
#if OHAttributedLabel_WarnAboutKnownIssues
[self warnAboutKnownIssues_CheckLineBreakMode];
#endif
}
-(void)setCenterVertically:(BOOL)val
{
_centerVertically = val;
[self setNeedsDisplay];
}
-(void)setAutomaticallyAddLinksForType:(NSTextCheckingTypes)types
{
_automaticallyAddLinksForType = types;
[self recomputeLinksInText];
}
-(void)setLinkColor:(UIColor *)newLinkColor
{
#if ! __has_feature(objc_arc)
[_linkColor release];
_linkColor = [newLinkColor retain];
#else
_linkColor = newLinkColor;
#endif
[self recomputeLinksInText];
}
-(void)setUnderlineLinks:(BOOL)newValue
{
_underlineLinks = newValue;
[self recomputeLinksInText];
}
-(void)setExtendBottomToFit:(BOOL)val
{
_extendBottomToFit = val;
[self setNeedsDisplay];
}
-(void)setNeedsDisplay
{
[self resetTextFrame];
[super setNeedsDisplay];
}
/////////////////////////////////////////////////////////////////////////////////////
#pragma mark - UILabel unsupported features/known issues warnings
/////////////////////////////////////////////////////////////////////////////////////
#if OHAttributedLabel_WarnAboutKnownIssues
-(void)warnAboutKnownIssues_CheckLineBreakMode
{
BOOL truncationMode = (self.lineBreakMode == UILineBreakModeHeadTruncation)
|| (self.lineBreakMode == UILineBreakModeMiddleTruncation)
|| (self.lineBreakMode == UILineBreakModeTailTruncation);
if (truncationMode)
{
NSLog(@"[OHAttributedLabel] Warning: \"UILineBreakMode...Truncation\" lineBreakModes are not yet fully supported by CoreText and OHAttributedLabel");
NSLog(@" (truncation will appear on each paragraph instead of the whole text)");
NSLog(@" This is a known issue (Help to solve this would be greatly appreciated).");
NSLog(@" See https://github.com/AliSoftware/OHAttributedLabel/issues/3");
}
}
-(void)warnAboutKnownIssues_CheckAdjustsFontSizeToFitWidth
{
if (self.adjustsFontSizeToFitWidth)
{
NSLog(@"[OHAttributedLabel] Warning: \"adjustsFontSizeToFitWidth\" property not supported by CoreText. OHAttributedLabel will ignore this property.");
}
}
-(void)setAdjustsFontSizeToFitWidth:(BOOL)value
{
[super setAdjustsFontSizeToFitWidth:value];
[self warnAboutKnownIssues_CheckAdjustsFontSizeToFitWidth];
}
-(void)setNumberOfLines:(NSInteger)nbLines
{
if (nbLines > 0)
{
NSLog(@"[OHAttributedLabel] Warning: the numberOfLines property is not yet supported by CoreText, so this property is ignored by OHAttributedLabel.");
NSLog(@" This is a known issue (Help to solve this would be greatly appreciated).");
NSLog(@" See https://github.com/AliSoftware/OHAttributedLabel/issues/34");
NSLog(@" To remove this warning, set the numberOfLines property to 0.");
}
[super setNumberOfLines:nbLines];
}
#endif
@end