Search code examples
objective-cuitextfieldios7key-value-observing

Changing UITextField in UITableViewCell value does not trigger KVO in iOS 7


I have a UITableView that has cells containing text fields. As the user edits each text field, I need to keep track of the cell's text field value (even when the cell is no longer displayed, so simply tracking the text field does not work). So I used Key-Value Observing and set an observer for each text field in my UITableViewController subclass:

[cell addObserver:self forKeyPath:@"textField.text" options:NSKeyValueObservingOptionNew context:nil];

And save new changes to the text field in the class's observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context method.

This works great in iOS 6, but in iOS 7 KVO isn't called when the user changes the text field value. Apparently the setter method called by pressing "done" on the keyboard doesn't call KVO anymore.

Is there a workaround to this? Or a better way of listening for this change? I need to know what cell the text field belongs to, so implementing the text field's method editingDidEnd doesn't work for me.

Thanks in advance.


Solution

  • I'm not sure about whether there is a workaround for this or not but there surely is a better way of listening for the UITextField text value. If you are creating instances of UITextField programmatically, all you need to do is add an event handler for them to notify your class about the text changing events. For example:

    [myTextField addTarget:self action:@selector(editingChanged:) forControlEvents:UIControlEventEditingChanged];
    
    
    - (void)editingChanged:(UITextField *)sender {
      NSString *targetText = sender.text;
    }