-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMFJLabel.m
409 lines (336 loc) · 14.9 KB
/
MFJLabel.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
//
// MFJLabel.m
//
// Copyright (c) 2013 Malcolm Jarvis (github.com/mjarvis). All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#import "MFJLabel.h"
NSString * const MFJLabelLinkAttributeName = @"MFJLabelLinkAttributeName";
NSString * const MFJLabelPhoneNumberAttributeName = @"MFJLabelPhoneNumberAttributeName";
NSString * const MFJLabelAddressAttributeName = @"MFJLabelAddressAttributeName";
NSString * const MFJLabelDateAttributeName = @"MFJLabelDateAttributeName";
@interface MFJLabel () <UIGestureRecognizerDelegate>
@property (nonatomic, strong) NSDataDetector *dataDetector;
@property (nonatomic, assign) NSRange linkRange;
@property (nonatomic, weak) NSTimer *timer;
@end
@implementation MFJLabel
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self
action:@selector(longPress:)];
{
longPress.minimumPressDuration = 0.0;
longPress.delegate = self;
}
[self addGestureRecognizer:longPress];
self.userInteractionEnabled = YES;
self.lineBreakMode = NSLineBreakByWordWrapping;
_linkAttributes = @{
NSForegroundColorAttributeName: [UIColor blueColor],
NSBackgroundColorAttributeName: [[UIColor blackColor] colorWithAlphaComponent:0.2],
NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle),
NSUnderlineColorAttributeName: [UIColor blueColor],
};
_dataDetectorTypes = MFJDataDetectorTypeDate|MFJDataDetectorTypeAddress|MFJDataDetectorTypeLink|MFJDataDetectorTypePhoneNumber;
}
return self;
}
- (void)invalidateTextStorage
{
[self.timer invalidate];
self.linkRange = NSMakeRange(NSNotFound, 0);
self.textStorage = nil;
[self setNeedsDisplay];
}
- (void)ensureTextStorage
{
if (self.textStorage == nil)
{
self.textStorage = [self textStorageWithDetectedLinksForAttributedString:self.attributedText];
}
}
- (NSDataDetector *)dataDetector
{
if (_dataDetector == nil && _dataDetectorTypes != 0)
{
_dataDetector = [[NSDataDetector alloc] initWithTypes:_dataDetectorTypes
error:NULL];
}
return _dataDetector;
}
- (void)setText:(NSString *)text
{
[super setText:text];
[self invalidateTextStorage];
}
- (void)setAttributedText:(NSAttributedString *)attributedText
{
self.originalAttributedString = attributedText;
[super setAttributedText:attributedText];
[self invalidateTextStorage];
}
- (NSAttributedString *)attributedText
{
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:self.originalAttributedString];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
{
paragraphStyle.lineBreakMode = self.lineBreakMode;
paragraphStyle.alignment = self.textAlignment;
}
NSDictionary *attributes = @{
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: self.font,
NSForegroundColorAttributeName: self.textColor,
};
[string addAttributes:attributes
range:NSMakeRange(0, [string length])];
[self.originalAttributedString enumerateAttributesInRange:NSMakeRange(0, self.originalAttributedString.length)
options:NSAttributedStringEnumerationReverse
usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
if (attrs[MFJLabelLinkAttributeName] != nil)
{
[string addAttributes:self.linkAttributes range:range];
}
[string addAttributes:attrs range:range];
}];
return string;
}
- (void)setDataDetectorTypes:(MFJDataDetectorType)dataDetectorTypes
{
_dataDetectorTypes = dataDetectorTypes;
self.dataDetector = dataDetectorTypes ? [[NSDataDetector alloc] initWithTypes:dataDetectorTypes
error:NULL] : nil;
[self invalidateTextStorage];
}
- (void)setTextColor:(UIColor *)textColor
{
[super setTextColor:textColor];
[self invalidateTextStorage];
}
- (void)setTextStorage:(NSTextStorage *)textStorage
{
_textStorage = textStorage;
}
- (void)setFont:(UIFont *)font
{
[super setFont:font];
[self invalidateTextStorage];
}
- (void)setLineBreakMode:(NSLineBreakMode)lineBreakMode
{
[super setLineBreakMode:lineBreakMode];
[self invalidateTextStorage];
}
- (void)setTextAlignment:(NSTextAlignment)textAlignment
{
[super setTextAlignment:textAlignment];
[self invalidateTextStorage];
}
- (void)setLinkAttributes:(NSDictionary *)linkAttributes
{
_linkAttributes = linkAttributes;
[self invalidateTextStorage];
}
- (void)setLinkRange:(NSRange)linkRange
{
_linkRange = linkRange;
[self setNeedsDisplay];
}
- (NSTextStorage *)textStorageWithDetectedLinksForAttributedString:(NSAttributedString *)attributedString
{
if (attributedString == nil)
{
return nil;
}
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedString];
{
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
{
NSTextContainer *textContainer = [[NSTextContainer alloc] init];
{
textContainer.lineFragmentPadding = 0.0;
}
[layoutManager addTextContainer:textContainer];
}
[textStorage addLayoutManager:layoutManager];
if (self.dataDetector != nil)
{
NSArray *matches = [self.dataDetector matchesInString:[textStorage string]
options:0
range:NSMakeRange(0, [textStorage length])];
for (NSTextCheckingResult *match in matches)
{
NSMutableDictionary *linkAttributes = [self.linkAttributes ?: @{} mutableCopy];
{
switch (match.resultType)
{
case NSTextCheckingTypeLink:
linkAttributes[MFJLabelLinkAttributeName] = match.URL;
break;
case NSTextCheckingTypePhoneNumber:
linkAttributes[MFJLabelPhoneNumberAttributeName] = match.phoneNumber;
break;
case NSTextCheckingTypeAddress:
linkAttributes[MFJLabelAddressAttributeName] = match.addressComponents;
break;
case NSTextCheckingTypeDate:
linkAttributes[MFJLabelDateAttributeName] = match.date;
break;
default:
break;
}
}
[textStorage addAttributes:linkAttributes
range:[match range]];
}
}
}
return textStorage;
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
[self ensureTextStorage];
if (self.preferredMaxLayoutWidth > 0 && bounds.size.width > self.preferredMaxLayoutWidth)
{
bounds.size.width = self.preferredMaxLayoutWidth;
}
CGRect boundingRect = [self.textStorage boundingRectWithSize:bounds.size
options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
context:nil];
NSLayoutManager *layoutManager = [self.textStorage.layoutManagers firstObject];
NSTextContainer *textContainer = [layoutManager.textContainers firstObject];
boundingRect.size.width += textContainer.lineFragmentPadding * 2;
return CGRectIntegral(boundingRect);
}
- (void)drawTextInRect:(CGRect)rect
{
[self ensureTextStorage];
rect = [self textRectForBounds:self.bounds
limitedToNumberOfLines:0];
NSLayoutManager *layoutManager = [self.textStorage.layoutManagers firstObject];
NSTextContainer *textContainer = [layoutManager.textContainers firstObject];
textContainer.size = CGSizeMake(CGRectGetWidth(rect), CGFLOAT_MAX);
textContainer.lineBreakMode = self.lineBreakMode;
NSRange glyphRange = [layoutManager glyphRangeForTextContainer:textContainer];
rect.origin.y = CGRectGetMidY(self.bounds) - rect.size.height/2;
[layoutManager drawGlyphsForGlyphRange:glyphRange atPoint:rect.origin];
if (self.linkRange.location != NSNotFound)
{
[layoutManager drawBackgroundForGlyphRange:self.linkRange atPoint:rect.origin];
}
}
#pragma mark - Link Actions -
- (void)longPress:(UILongPressGestureRecognizer *)sender
{
if ([sender state] == UIGestureRecognizerStateBegan)
{
CGPoint location = [sender locationInView:self];
NSLayoutManager *layoutManager = [self.textStorage.layoutManagers firstObject];
NSTextContainer *textContainer = [layoutManager.textContainers firstObject];
NSUInteger glyphIndex = [layoutManager glyphIndexForPoint:location inTextContainer:textContainer];
NSUInteger characterIndex = [layoutManager characterIndexForGlyphAtIndex:glyphIndex];
CGRect boundingRect = [layoutManager boundingRectForGlyphRange:NSMakeRange(glyphIndex, 1)
inTextContainer:textContainer];
if (CGRectContainsPoint(boundingRect, location))
{
NSRange effectiveRange;
NSDictionary *attributes = [self.textStorage attributesAtIndex:characterIndex
effectiveRange:&effectiveRange];
self.linkRange = effectiveRange;
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.75
target:self
selector:@selector(timerFired:)
userInfo:attributes
repeats:NO];
}
}
else if ([sender state] == UIGestureRecognizerStateChanged)
{
CGPoint location = [sender locationInView:self];
NSLayoutManager *layoutManager = [self.textStorage.layoutManagers firstObject];
NSTextContainer *textContainer = [layoutManager.textContainers firstObject];
NSRange glyphRange = [layoutManager glyphRangeForCharacterRange:self.linkRange actualCharacterRange:nil];
CGRect rect = [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer];
if (CGRectContainsPoint(rect, location) == NO)
{
[self.timer invalidate];
self.linkRange = NSMakeRange(NSNotFound, 0);
}
}
else if ([sender state] == UIGestureRecognizerStateEnded)
{
[self.timer invalidate];
if (self.linkRange.location != NSNotFound)
{
[self shortPress:sender];
self.linkRange = NSMakeRange(NSNotFound, 0);
}
}
}
- (void)shortPress:(UILongPressGestureRecognizer *)sender
{
NSString *linkText = [self.text substringWithRange:self.linkRange];
NSDictionary *attributes = [self.textStorage attributesAtIndex:self.linkRange.location
effectiveRange:NULL];
[self.delegate label:self
didTapLinkText:linkText
withAttributes:attributes];
}
- (void)timerFired:(NSTimer *)timer
{
NSString *linkText = [self.text substringWithRange:self.linkRange];
NSDictionary *attributes = [timer userInfo];
self.linkRange = NSMakeRange(NSNotFound, 0);
[self.delegate label:self
didLongPressLinkText:linkText
withAttributes:attributes];
}
#pragma mark - UIGestureRecognizerDelegate -
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if ([self.textStorage length] == 0)
{
return NO;
}
CGPoint location = [touch locationInView:self];
NSLayoutManager *layoutManager = [self.textStorage.layoutManagers firstObject];
NSTextContainer *textContainer = [layoutManager.textContainers firstObject];
NSUInteger glyphIndex = [layoutManager glyphIndexForPoint:location inTextContainer:textContainer];
NSUInteger characterIndex = [layoutManager characterIndexForGlyphAtIndex:glyphIndex];
CGRect boundingRect = [layoutManager boundingRectForGlyphRange:NSMakeRange(glyphIndex, 1)
inTextContainer:textContainer];
if (CGRectContainsPoint(boundingRect, location) == NO)
{
return NO;
}
NSRange effectiveRange;
NSDictionary *attributes = [self.textStorage attributesAtIndex:characterIndex
effectiveRange:&effectiveRange];
return (attributes[MFJLabelLinkAttributeName] || attributes[MFJLabelPhoneNumberAttributeName] || attributes[MFJLabelAddressAttributeName] || attributes[MFJLabelDateAttributeName]);
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
@end