Jiahao Li
Jiahao Li

Reputation: 101

UITextField fires UITextFieldTextDidChangeNotification when changed by code?

I'm trying to add a UIViewController to be the observer of the UITextFieldTextDidChangeNotification notification. When I change the text through typing in the text field, everything goes smoothly. However, if I try to change the text by calling [_textfield setText:@"Blahblah"], the notification doesn't seem to be fired.

Is this the intended way?

Thanks!

Upvotes: 3

Views: 981

Answers (1)

rmaddy
rmaddy

Reputation: 318814

This is generally true of most events. You want the notification when the event is user driven. But when the event is driven by an explicit code change, you don't want the notification. Since you are making an explicit call to make the change, you can optionally also call the notification handler. This is a more flexible approach.

Here's an example of why you don't want the notification to be sent when your own code would trigger the event. Imagine that when your code gets the notification, you validate the text and based on the validation, you update the text field. This could result in an infinite loop of notify/change.

Upvotes: 6

Related Questions