简体   繁体   English

点击手势到UITextView的一部分

[英]Tap gesture to part of a UITextView

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? 这将对整个UITextView做出反应,但是是否可以更改它,使其仅在敲击UITextView中的字符串的特定部分时才响应? Like a URL for example? 例如网址?

You cannot assign tap gesture to particular string in normal UITextView. 您无法在普通的UITextView中将敲击手势指定给特定字符串。 You can probably set the dataDetectorTypes for UITextView. 您可以为UITextView设置dataDetectorTypes。

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 . 有关更多详细信息,请查阅文档: UIKit DataTypes Reference Also check this Documentation on UITextView 还要在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. 您可以尝试使用粒度,例如UITextGranularitySentence,UITextGranularityLine等。请在此处查看文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM