Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 823
user265961 Avatar asked Oct 14 '22 17:10

user265961


2 Answers

-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]];
like image 273
Vladimir Avatar answered Oct 17 '22 07:10

Vladimir


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSLog(@"%@",searchStr);
    return YES;
}
like image 52
btmanikandan Avatar answered Oct 17 '22 07:10

btmanikandan