-
Notifications
You must be signed in to change notification settings - Fork 4
/
UTTouchDetectingLabel.m
96 lines (75 loc) · 2.36 KB
/
UTTouchDetectingLabel.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
//
// UTTouchDetectingLabel.m
// RingFinder
//
// Created by Danny Morrow on 7/2/13.
// Copyright (c) 2013 unitytheory. All rights reserved.
//
#import "UTTouchDetectingLabel.h"
@implementation UTTouchDetectingLabel
@synthesize dataDetectorTypes = _dataDetectorTypes;
@synthesize linkAttributes = _linkAttrbutes;
@synthesize tappedLinkAttributes;
- (void) setDataDetectorTypes:(NSTextCheckingTypes )dataDetectorTypes
{
if (_dataDetectorTypes != dataDetectorTypes)
{
_dataDetectorTypes = dataDetectorTypes;
[self findLinks];
}
}
- (void) setText:(NSString *)text
{
[super setText:text];
[self findLinks];
}
- (void) setAttributedText:(NSAttributedString *)attributedText
{
[super setAttributedText:attributedText];
[self findLinks];
}
- (void) setLinkAttributes:(NSDictionary *)attributes
{
_linkAttrbutes = attributes;
[self styleLinks];
}
- (void) findLinks
{
if (_dataDetectorTypes == UIDataDetectorTypeNone) return;
if (self.text.length == 0) return;
NSError* error;
NSDataDetector *detector = [NSDataDetector
dataDetectorWithTypes:_dataDetectorTypes
error:&error];
_linkRanges = nil;
NSArray *links = [detector matchesInString:self.text
options:0
range:NSMakeRange(0, [self.text length])];
if ([links count] > 0)
{
NSMutableIndexSet *tempRanges = [NSMutableIndexSet indexSet];
for (NSTextCheckingResult *match in links)
{
[tempRanges addIndexesInRange:[match range]];
}
_linkRanges = [tempRanges copy];
self.userInteractionEnabled = TRUE;
}
[self styleLinks];
}
- (void) styleLinks
{
if ([_linkRanges count] == 0) return;
if (_linkAttrbutes && [self respondsToSelector:@selector(setAttributedText:)])
{
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:self.text];
[_linkRanges enumerateRangesUsingBlock:^(NSRange range, BOOL *stop){
for (NSString* key in _linkAttrbutes)
{
[string addAttribute:key value:[self.linkAttributes valueForKey:key] range:range];
}
}];
self.attributedText = string;
}
}
@end