我正在实现一个列表,可以在 UITextFieldDelegate
的帮助下使用 UITextField
中的文本进行过滤。
代码如下:
- (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];
}
}
在输入文本时过滤器工作得很好;但是,当 按下 DONE 键盘键(隐藏键盘),这会奇怪地删除所有项目,而不是保持原样。
问题是 rangeOfString
部分始终返回 NSNotFound。我不明白为什么,如果我记录变量,两个字符串都是正确的。
例如:
[@"Angola"rangeOfString @"A"].location
将给出 NSNotFound
我再说一遍,这只在键盘隐藏时才会发生。有人有想法吗?
提前致谢
最佳答案
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
按下完成按钮时不会触发,否则如果您强制调用此函数。
用它来隐藏键盘,这不会触发上面的方法。
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
关于iphone - 隐藏键盘时 NSString rangeOfString 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10939733/