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?
-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]];
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSLog(@"%@",searchStr);
return YES;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With