I have a table view. In cellForRowAtIndexPath
I have a cell and in that cell there is UITextField. I set textfield's delegate like this: cell.textField.delegate = self;
. I need to call my API on third character. So when user types 3 character in textfield, API is called hence shouldChangeCharactersInRange
.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField.text.length >= 2) {
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring
stringByReplacingCharactersInRange:range withString:string];
[API CALLED WITH BLOCK WITH TEXTFIELD TEXT AS PARAMETER:substring];
}
return YES;
}
The problem is that when I type for example "abc" shouldChangeCharactersInRange
is called first time and parameter is "abc". Second after, shouldChangeCharactersInRange
is again called and my textfield has another added character which I did not type and it is always last character that is copied. So in this example, it sends "abcc". Do you know, what is the problem?
Setting breakpoints in that delegate method can sometimes cause the method to be fired twice. Try removing any breakpoints that are hit here or in your API method and test again.
This can be replicated easily. Create a new project, add a UITextField
outlet and set the delegate to your controller. Implement textField:shouldChangeCharactersInRange:
in your controller and set a breakpoint on an NSLog
statement or something, and return YES
. Sometimes, after telling the debugger to continue, a second keystroke will be generated and will hit your delegate method again.
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