2

我有这个代码:

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

这将对整个 UITextView 做出反应,但是否可以对其进行更改,使其仅在点击 UITextView 中字符串的某个部分时做出响应?例如,像一个 URL?

4

1 回答 1

7

您不能将点击手势分配给普通 UITextView 中的特定字符串。您可能可以为 UITextView 设置 dataDetectorTypes。

textview.dataDetectorTypes = UIDataDetectorTypeAll;

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

textview.dataDetectorTypes = UIDataDetectorTypeLink;

查看文档以获取更多详细信息: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
}

从此使用:

- (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 等粒度。在此处查看文档

于 2013-02-22T23:04:34.593 回答