Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UITextView Event Listener

Tags:

swift

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.

like image 883
Jacob Wilson Avatar asked Apr 27 '16 01:04

Jacob Wilson


1 Answers

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.

like image 145
Evdzhan Mustafa Avatar answered Sep 19 '22 21:09

Evdzhan Mustafa