点击手势到UITextView的一部分

时间:2013-02-22 23:02:11

标签: ios nsstring uitextview uitapgesturerecognizer

我有这段代码:

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

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

1 个答案:

答案 0 :(得分:7)

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

textview.dataDetectorTypes = UIDataDetectorTypeAll;

如果您只想检测网址,可以指定

textview.dataDetectorTypes = UIDataDetectorTypeLink;

查看文档以获取更多详细信息:UIKit DataTypes Reference。另请查看此Documentation on 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
}

this开始,使用:

- (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];
}

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