I am implementing a list that can be filtered with the text from a UITextField, with the help of a UITextFieldDelegate.
The code is the following:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
_tempWrittenText = [textField.text stringByReplacingCharactersInRange: range withString: string];
[self filterCountries];
return YES;
}
/** Filter the countries with the currently typed text */
- (void) filterCountries {
if (_tempWrittenText.length == 0) {
_visibleCountriesList = (NSMutableArray*) _countriesList;
[tableMedals reloadSections: [NSIndexSet indexSetWithIndex: 0] withRowAnimation: UITableViewRowAnimationNone];
} else {
_visibleCountriesList = [NSMutableArray array];
for (Country* c in _countriesList) {
if ([c.name rangeOfString: _tempWrittenText].location != NSNotFound) {
[_visibleCountriesList addObject: c];
}
}
[tableMedals reloadSections: [NSIndexSet indexSetWithIndex: 0] withRowAnimation: UITableViewRowAnimationFade];
}
}
The filter works perfectly when typing on text; however, the - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string method is also fired when the DONE keyboard key is pressed (to hide the keyboard), which weirdly erases all items instead of leaving them as they are.
The issue is that the rangeOfString part is ALWAYS returning NSNotFound. I can’t understand why, if I log the variables the two strings are correct.
For example:
[@"Angola" rangeOfString @"A"].location will give NSNotFound
And I repeat, this only happens when the keyboard is hidden. Anyone has an Idea?
Thanks in advance
The
is not fired when done button is pressed, otherwise if you force to call this function.
Use this to hide the keyboard, this will not trigger above method.