UITextViewでのタップがattributedTextでNSLinkAttributeNameを指定したリンク文のタップか確認
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
| - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { if (touches.count > 1) { return; } UITouch *touch = touches.anyObject; CGPoint point = [touch locationInView:self];
BOOL linkTouched = [self checkTouchedPoint:point]; }
- (BOOL)checkTouchedPoint:(CGPoint)point { NSUInteger touchedLocation; NSURL *touchedUrl;
UITextPosition *postion = [self closestPositionToPoint:point]; UITextRange *range = [self.tokenizer rangeEnclosingPosition:postion withGranularity:UITextGranularityCharacter inDirection:UITextLayoutDirectionLeft]; NSInteger offset = [self offsetFromPosition:self.beginningOfDocument toPosition:range.start]; id value = [self.attributedText attribute:NSLinkAttributeName atIndex:offset effectiveRange:nil]; NSURL *url = [NSURL URLWithString:value]; if (url) { __block BOOL isLink = NO; NSUInteger glyphIndex = [self.layoutManager glyphIndexForCharacterAtIndex:offset]; [self.layoutManager enumerateLineFragmentsForGlyphRange:NSMakeRange(glyphIndex, 1) usingBlock:^(CGRect rect, CGRect usedRect, NSTextContainer * _Nonnull textContainer, NSRange glyphRange, BOOL * _Nonnull stop) { if (CGRectContainsPoint(usedRect, point)) { isLink = YES; *stop = YES; } }]; if (isLink) { touchedUrl = url; touchedLocation = offset; return YES; } } return NO; }
|