点击手势到UITextView的一部分

jwk*_*knz 2 nsstring uitextview ios uitapgesturerecognizer

我有这个代码:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapResponse)];
singleTap.numberOfTapsRequired = 1;
[_textView addGestureRecognizer:singleTap];
Run Code Online (Sandbox Code Playgroud)

这将对整个UITextView作出反应,但是是否可以更改它以便它只响应UITextView中字符串的某个部分被点击?比如一个URL?

iDe*_*Dev 7

您无法在普通的UITextView中将敲击手势指定给特定字符串.您可以为UITextView设置dataDetectorTypes.

textview.dataDetectorTypes = UIDataDetectorTypeAll;
Run Code Online (Sandbox Code Playgroud)

如果您只想检测网址,可以分配给,

textview.dataDetectorTypes = UIDataDetectorTypeLink;
Run Code Online (Sandbox Code Playgroud)

有关此内容的更多详细信息,请查看文档:UIKit DataTypes Reference.另请在UITextView上查看此文档

更新:

根据您的评论,请检查如下:

- (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
}
Run Code Online (Sandbox Code Playgroud)

这里,使用:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

您可以尝试使用粒度,例如UITextGranularitySentence,UITextGranularityLine等.请在此处查看文档.