Tap gesture to part of a UITextView
Asked Answered
H

1

2

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?

Hubie answered 22/2, 2013 at 23:2 Comment(0)
R
7

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.

Ragsdale answered 22/2, 2013 at 23:4 Comment(8)
that will display the link, but the gesture will react to all of the textViewHubie
Yes. Once you tap on the link, it will open corresponding application based on the url scheme.Ragsdale
Yeah but with a URL it open in safari, with a UITapGesture, I was hoping to have it open in my UIWebViewHubie
Updated my answer. Check with that.Ragsdale
Cool will have a play with that and update my answer in a bit:-)Hubie
Try with different granularity options and you can update my answer with which ever worked for you. But this should guide you to right direction.Ragsdale
Yes this definitely put me on the right path thanks:-) I just work out the final few little bits.Hubie
Why do you remake the CGPoint in tapResponse:?Accumulative

© 2022 - 2024 — McMap. All rights reserved.