Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Links to TextView with the possibility of editing TextView (Swift 4)

I have a TextView.

How can I make it so that both the links work and you could edit TextView?

how can I make it so that when I post a link to TextView then it would be possible to click on it and go over it (and highlight it with a different color).

I tried to include Link in the settings but then TextView can not be edited.

enter image description here

like image 389
B2Fq Avatar asked Dec 10 '17 10:12

B2Fq


Video Answer


1 Answers

To be able to detect links from your textView you need to have editable set to false. What you can do is to add a gesture recognizer to your textView to detect clicks and that gesture recognizer will ignore cliks on links. Example below (read the comments for explanations):

class ViewController: UIViewController, UITextViewDelegate {
    // create an outlet for your textView
    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        textView.delegate = self

        // add a tap gesture to your textView
        let tap = UITapGestureRecognizer(target: self, action: #selector(textViewTapped))
        textView.addGestureRecognizer(tap)

        //add a tap recognizer to stop editing when you tap outside your textView (if you want to)
        let viewTap = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
        self.view.addGestureRecognizer(viewTap)
    }

    @objc func viewTapped(_ aRecognizer: UITapGestureRecognizer) {
        self.view.endEditing(true)
    }

    // when you tap on your textView you set the property isEditable to true and you´ll be able to edit the text. If you click on a link you´ll browse to that link instead
    @objc func textViewTapped(_ aRecognizer: UITapGestureRecognizer) {
        textView.dataDetectorTypes = []
        textView.isEditable = true
        textView.becomeFirstResponder()
    }

    // this delegate method restes the isEditable property when your done editing
    func textViewDidEndEditing(_ textView: UITextView) {
        textView.isEditable = false
        textView.dataDetectorTypes = .all
    }
}

The textView has the following properties: enter image description here

And here is a link to the sample project I created.

like image 52
Rashwan L Avatar answered Nov 15 '22 07:11

Rashwan L