点击 UITextView 打开 link

UITextView open link on tap

我使用这个代码:

var textView = UITextView(x: 10, y: 10, width: CardWidth - 20, height: placeholderHeight) //This is my custom initializer
textView.text = "dsfadsaf www.google.com"
textView.selectable = true
textView.dataDetectorTypes = UIDataDetectorTypes.Link
textView.delegate = self
addSubview(textView)

问题是 link 需要长按手势才能打开。我希望它可以通过单击打开,就像在 Facebook 应用程序中一样。

以下示例仅适用于 iOS 8+

点击识别器:

let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("tappedTextView:"))
myTextView.addGestureRecognizer(tapRecognizer)
myTextView.selectable = true

回调:

func tappedTextView(tapGesture: UIGestureRecognizer) {

    let textView = tapGesture.view as! UITextView
    let tapLocation = tapGesture.locationInView(textView)
    let textPosition = textView.closestPositionToPoint(tapLocation)
    let attr: NSDictionary = textView.textStylingAtPosition(textPosition, inDirection: UITextStorageDirection.Forward)

    if let url: NSURL = attr[NSLinkAttributeName] as? NSURL {
        UIApplication.sharedApplication().openURL(url)
    }

}

Swift 3 且无力展开:

func tappedTextView(tapGesture: UIGestureRecognizer) {
        guard let textView = tapGesture.view as? UITextView else { return }
        guard let position = textView.closestPosition(to: tapGesture.location(in: textView)) else { return }
        if let url = textView.textStyling(at: position, in: .forward)?[NSLinkAttributeName] as? URL {
            UIApplication.shared.open(url)
        }
    }