Monday, November 30, 2009

iPhone dev Stupidity 110: Fine Grained Observing for Text Field

1. Using Key-value Observing to get update for a UITextField editing like this:

[nameField_ addObserver: self forKeyPath: @"text" options: NSKeyValueObservingOptionPrior context: nil];

You will only get the observing method (- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context) called when the edit is done - the text field lost focus.

2. To observe each character input, we need NSNotificationCenter (from apple forum):

[[NSNotificationCenter defaultCenter] addObserver: self  selector: @selector(textFieldTextDidChange:) name: @"UITextFieldTextDidChangeNotification"  object: nil];


where to find out the @"UITextFieldDidChangeNotification" string? It's in the UITextField.h:

UIKIT_EXTERN NSString *const UITextFieldTextDidBeginEditingNotification;


UIKIT_EXTERN NSString *const UITextFieldTextDidEndEditingNotification;


UIKIT_EXTERN NSString *const UITextFieldTextDidChangeNotification;


and sure apple had started iPhone SDK in 2005:


//  UITextField.h


//  UIKit


//


//  Copyright 2005-2009 Apple Inc. All rights reserved.


No comments: