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.
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:
And here is a link to the sample project I created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With