Ios 文本视图段落内的超链接/URL

Ios 文本视图段落内的超链接/URL,ios,iphone,swift,url,hyperlink,Ios,Iphone,Swift,Url,Hyperlink,我有一个段落是文本视图。我想在段落中的一些单词中添加超链接 var attributedString = NSMutableAttributedString(string: text) attributedString.addAttribute(NSLinkAttributeName, value: hyperlink, range: range) var linkAttributes = [NSForegroundColorAttributeName: UIColor.blueColor()

我有一个段落是文本视图。我想在段落中的一些单词中添加超链接

var attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSLinkAttributeName, value: hyperlink, range: range)

var linkAttributes = [NSForegroundColorAttributeName: UIColor.blueColor(),
            NSUnderlineStyleAttributeName: 1
        ]

textView!.linkTextAttributes = linkAttributes        
textView!.attributedText = attributedString
textView!.delegate = self

UITextViewDelegate

func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
    if UIApplication.sharedApplication().canOpenURL(URL) {
        return true
    } else {
        CozyStyles.alert(title: "Sorry", message: (URL.scheme!).capitalizeFirst + " is not installed", action: "OK")
        return false
    }
}
这种方法可行,但效果还不够好。简单录制时,它无法识别textView点击。该链接必须长期按下,使其工作,这是不是用户友好

这有什么办法吗

  • 解决方案也不起作用,因为我有另一个点击手势

一个类似于您提供的链接中的点击手势解决方案的附加点击手势解决方案应该可以工作,即使您当前有另一个点击手势

如果您的textView位于视图层次结构的顶部,则添加到textView的附加手势识别器应该只识别点击

如果将现有的点击手势添加到文本视图顶部的视图中,则可以实现UIgestureRecognitizerDelegate的shouldReceiveTouch方法,并在点击文本视图时处理点击,同时拒绝该手势接收触摸。 如果是这种情况,那么您甚至不需要额外的手势:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    CGPoint location = [touch locationInView:self.view];
    if (CGRectContainsPoint(self.textView.frame, location)) {
        [self handleTapOnTextViewAtLocation:[self.view convertPoint:location toView:self.textView]];
        return NO;
    }
    return YES;
}

- (void)handleTapOnTextViewAtLocation:(CGPoint)location {
    UITextPosition *textPosition = [self.textView closestPositionToPoint:location];
    NSDictionary *textStyling = [self.textView textStylingAtPosition:textPosition inDirection:UITextStorageDirectionForward];
    NSURL *url = textStyling[NSLinkAttributeName];
    if (url) {
        NSLog(@"url tapped: %@", url);
    }
}
使用此代码:

textView.dataDetectorTypes = UIDataDetectorTypeLink;

你确定你当前的轻触姿势不是破坏东西的动作吗?它可能在吸收水龙头。@Firo它不会影响它。当我注释掉另一个手势时也会发生同样的情况。这不允许我提供自定义超链接。