问题
I have this code:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapResponse)];
singleTap.numberOfTapsRequired = 1;
[_textView addGestureRecognizer:singleTap];
This will react to the entire UITextView, but is it possible to change it so that it only responds to when a certain part of the string in the UITextView is tapped? Like a URL for example?
回答1:
You cannot assign tap gesture to particular string in normal UITextView. You can probably set the dataDetectorTypes for UITextView.
textview.dataDetectorTypes = UIDataDetectorTypeAll;
If you want to detect only urls, you can assign to,
textview.dataDetectorTypes = UIDataDetectorTypeLink;
Check the documentation for more details on this: UIKit DataTypes Reference. Also check this Documentation on UITextView
Update:
Based on your comment, check like this:
- (void)tapResponse:(UITapGestureRecognizer *)recognizer
{
CGPoint location = [recognizer locationInView:_textView];
NSLog(@"Tap Gesture Coordinates: %.2f %.2f", location.x, location.y);
NSString *tappedSentence = [self lineAtPosition:CGPointMake(location.x, location.y)];
//use your logic to find out whether tapped Sentence is url and then open in webview
}
From this, use:
- (NSString *)lineAtPosition:(CGPoint)position
{
//eliminate scroll offset
position.y += _textView.contentOffset.y;
//get location in text from textposition at point
UITextPosition *tapPosition = [_textView closestPositionToPoint:position];
//fetch the word at this position (or nil, if not available)
UITextRange *textRange = [_textView.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularitySentence inDirection:UITextLayoutDirectionRight];
return [_textView textInRange:textRange];
}
You can try with granularities such as, UITextGranularitySentence, UITextGranularityLine etc.. Check the documentation here.
来源:https://stackoverflow.com/questions/15034652/tap-gesture-to-part-of-a-uitextview