点击手势到UITextView的一部分 [英] Tap gesture to part of a UITextView

查看:339
本文介绍了点击手势到UITextView的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

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

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

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? Like a URL for example?

推荐答案

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

You cannot assign tap gesture to particular string in normal UITextView. You can probably set the dataDetectorTypes for UITextView.

textview.dataDetectorTypes = UIDataDetectorTypeAll;

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

If you want to detect only urls, you can assign to,

textview.dataDetectorTypes = UIDataDetectorTypeLink;

查看文档以获取更多详细信息: UIKit DataTypes Reference 。另请检查 UITextView上的文档

Check the documentation for more details on this: UIKit DataTypes Reference. Also check this Documentation on UITextView

更新:

根据你的评论,检查如下:

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
}

这个,使用:

- (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等。检查文档这里。

You can try with granularities such as, UITextGranularitySentence, UITextGranularityLine etc.. Check the documentation here.

这篇关于点击手势到UITextView的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆