1

I would like to make all my UITextViews handle link clicks by opening a web view, rather than opening safari. How can I override this delegate function for all UITextViews within my app:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool

The code I want to put in it is the following:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
    let webViewController = WebViewController()
    webViewController.urlToLoad = URL
    present(webViewController, animated: true)
    return false
}
Tometoyou
  • 7,792
  • 12
  • 62
  • 108

2 Answers2

0

As far as I understood there are two things that you want to do:

  1. Override a function in all your UITextViews
  2. Presenting a WebViewController after handling the event

To override your function just create an UITextView extension that implements your delegate and set up each UITextView delegate to be itself:

extension UITextView: UITextViewDelegate {
    public func textView(_ textView: UITextView,
                  shouldInteractWith URL: URL,
                  in characterRange: NSRange) -> Bool {
        let webViewController = WebViewController()
        webViewController.urlToLoad = URL
        parentViewController.present(webViewController, animated: true)
        return false
    }
}

To do the second part you should use a delegate between your textfield and its parentViewController.

Its important to highlight that the extension will allow you to implement the method among all your UITextView but by default, you don't have access to the parentViewController inside an UITextView, so you need to implement the delegation correctly to be able to execute parentViewController.present(webViewController, animated: true)

jvrmed
  • 834
  • 6
  • 12
-1

You can achieve the same result through making a separate class which conforms UITextViewDelegate like:

class MyTextViewDelegate:NSObject, UITextViewDelegate
{
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool
    {
        //code for opening in UIWebView
        return true
    }
}

And use it like so:

let myTextViewDelegate = MyTextViewDelegate()
let textView = UITextView()
textView.delegate = myTextViewDelegate
Ayman Ibrahim
  • 1,359
  • 15
  • 24