如何在 UIWebView 中打开一个 link

How to open a link in UIWebView

我有一个聊天应用程序,偶尔会收到 link。单击 link,我可以在 Safari 中查看网页,我想在我的应用程序的 UIWebview 中打开 link。

我正在经历 this article,一切都很好,但它给出了硬编码 link。我希望能够打开用户刚刚点击的 link。实现此目标的最佳方法是什么?

基本上,您需要先让您的textView识别网址

textView.text = "example www.google.com"
textView.isSelectable = true
textView.dataDetectorTypes = UIDataDetectorTypes.link

但是在委托方法 shouldInteractWithURL 中,return false 这样你的 URL 是可点击的但你不会跳转到 Safari。

extension ViewController: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        print(url)
        //load url to YOUR web view here!
        return false
    }
}

别忘了设置委托!

textView.delegate = self

只需为 UITextView 设置一个委托并实现此功能:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    // open URL in UIWebView
}

记得扩展 UITextViewDelegate 并将委托设置为自己:

@IBOutlet var textview: UITextView!
class SomeVC: UIViewController, UITextViewDelegate {
   override func viewDidLoad() {
    super.viewDidLoad()
    textview.delegate = self
   }
}