Using `textField:shouldChangeCharactersInRange:`, how do I get the text including the current typed character?

user265961 picture user265961 · Feb 4, 2010 · Viewed 92.5k times · Source

I'm using the code below to try and have textField2's text content get updated to match textField1's whenever the user types in textField1.

- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {    
  if (theTextField == textField1){    
     [textField2 setText:[textField1 text]];    
  }
}

However, the output I observe is that...

textField2 is "12", when textField1 is "123"

textField2 is "123", when textField1 is "1234"

... when what I want is:

textField2 is "123", when textField1 is "123"

textField2 is "1234", when textField1 is "1234"

What am I doing wrong?

Answer

Vladimir picture Vladimir · Feb 4, 2010

-shouldChangeCharactersInRange gets called before text field actually changes its text, that's why you're getting old text value. To get the text after update use:

[textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]];