Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the Value of a UITextField as keystrokes are entered?

Let's say I have the following code:

IBOutlet UITextField* nameTextField; IBOutlet UILabel* greetingLabel; 

I'd like the greetingLabel to read "Hello [nameTextField]" as soon as the user presses any key.

What I need basically is the iPhone equivalent of the Cocoa delegate method controlTextDidChange.

The textField:shouldChangeCharactersInRange: delegate method is called each time a keystroke occurs:

- (BOOL)              textField:(UITextField *)textField   shouldChangeCharactersInRange:(NSRange)range                    replacementString:(NSString *)string 

The string argument returns the character that is pressed. The actual textField's value (nameTextField.text) remains blank however.

What am I missing here? (I'd like nameTextField to reflect the exact string that the user has entered so far).

like image 357
Debajit Avatar asked Dec 23 '08 05:12

Debajit


1 Answers

It turns out, the easiest way to do this is using Interface Builder:

  • Add a IBAction (to the ViewController, say, as in this case)
  • Ctrl-Click (or right click) on the UITextField in Interface Builder
  • Connect the "Editing Changed" event to the File's Owner's IBAction added in the first step.

Works like a charm :) (I can't believe I spent numerous days on this, and to realize now that the solution was much simpler than I'd thought :P)

like image 151
Debajit Avatar answered Nov 16 '22 00:11

Debajit