[swift]UITextView 上tap打开链接

发布时间: 2015/9/4 6:14:01
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我使用这段代码:

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)

问题是链接需要长的手势来打开。我希望它需一次点击,就像在 Facebook 应用程序中打开。

解决方法 1:

下面的示例仅适用于 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)
    }

}
官方微信
官方QQ群
31647020