4

Text Editor

What I'm Doing

Text View

I am attempting to create a UITextView that is a code editor on IOS and I am trying to make different types of code be different colors so everything isn't just one color (such as comments would be grey).

Problem

The problem I am having is that I am linking the Text View like this:

@IBOutlet weak var textView: UITextView!

and I need to detect when the textView has been changed do you know of any way to do this?

Community
  • 1
  • 1

2 Answers2

7

To do this, you need to conform to the UITextViewDelegate protocol and then set the textView's delegate to self.

So, after UIViewController on the beginning of this view controller, you need to add the protocol conformance. Example

class MyViewController: UIViewController, UITextViewDelegate {

then set the delegate in viewDidLoad():

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

Now, you're set up for success. All of the delegate methods on UITextViewDelegate are optional, so you only need to implement the ones you want. In this case, the one you want to implement is func textViewDidChange(_ textView: UITextView)

That method will get triggered every single time the text in the text field updates.

jakehawken
  • 707
  • 7
  • 12
4

Create Editing Changed @IBAction from your UITextView in storyBoard into your viewController.

enter image description here

Arash Etemad
  • 1,827
  • 1
  • 13
  • 29