8

My question is how would I set an event listener to listen if the user has typed a character into a UITextView?

I know I can use textview.hasText() to check if it has text but I need to listen for a character typed even if there is already text in the UITextView.

Jacob Wilson
  • 430
  • 1
  • 5
  • 12
  • This `UITextView `placeholder answer provides a simple functional example of how to use a `UITextViewDelegate` ... http://stackoverflow.com/questions/27652227/text-view-placeholder-swift/28271069#28271069 – clearlight Feb 02 '17 at 02:03

1 Answers1

10

Have a look at UITextViewDelegate.

For example if you have

@IBOutlet weak var textView: UITextView!;

Do conform to the UITextViewDelegate protocol in your view controller

class ViewController: UIViewController, UITextViewDelegate {

// stuff
}

In your viewDidLoad method add

textView.delegate = self;

Then depending on what you want to listen for, implement the methods from UITextViewDelegate you need.

For example, if you want to listen for when the text view changed implement:

func textViewDidEndEditing(textView: UITextView) {
    // your code here.
    print(textView.text);
}

Edit: To reflect on the comment do implement this method:

func textViewDidChange(textView: UITextView) {

}

From Apple's documentation:

Tells the delegate that the text or attributes in the specified text view were changed by the user.

Evdzhan Mustafa
  • 3,645
  • 1
  • 24
  • 40
  • This is close but I don't think it's quite right for what I need to accomplish. I don't want to listen for `textViewDidEndEditing()` because that would imply that they keyboard closed and editing stopped when I need to listen while editing is in process and the keyboard open. – Jacob Wilson Apr 27 '16 at 01:41
  • I looked around on Apple's documentation and found `textViewDidChange(_ textView: UITextView)`. This may be what I'm looking for. – Jacob Wilson Apr 27 '16 at 01:44