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 に答える