【问题标题】:UITextView open link on tapUITextView 点击打开链接
【发布时间】:2015-09-11 06:08:00
【问题描述】:

我使用这个代码:

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 应用程序中一样,只需轻按一下即可打开。

【问题讨论】:

标签: ios swift uiwebview uitextview datadetectortypes


【解决方案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)
    }

}

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)
        }
    }

【讨论】:

  • 在 Swift 4 中无法使用密钥 NSLinkAttributeName。一个简单的解决方法是改用密钥 "NSLink"
  • 非常感谢。我无法使用 shouldInteractWithURL,它与我的手势识别器冲突(如果单击链接,我无法取消手势操作)。所以我在手势识别器中做了你的回答
猜你喜欢
  • 1970-01-01
  • 2015-09-16
  • 2014-04-18
  • 2012-07-28
  • 1970-01-01
  • 2018-02-18
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
相关资源
最近更新 更多