【问题标题】:Tap gesture to part of a UITextView点击手势到 UITextView 的一部分
【发布时间】:2013-02-08 16:32:13
【问题描述】:

我有这个代码:

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

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

【问题讨论】:

    标签: ios nsstring uitextview uitapgesturerecognizer


    【解决方案1】:

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

    textview.dataDetectorTypes = UIDataDetectorTypeAll;
    

    如果你只想检测 url,你可以分配到,

    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

    【讨论】:

    • 将显示链接,但手势将对所有 textView 做出反应
    • 是的。一旦你点击链接,它将根据 url 方案打开相应的应用程序。
    • 是的,但是它在 safari 中打开一个 URL,使用 UITapGesture,我希望在我的 UIWebView 中打开它
    • 更新了我的答案。检查一下。
    • Cool 会玩这个,并在稍后更新我的答案:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 2011-08-10
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多