【发布时间】:2012-06-07 20:55:46
【问题描述】:
我正在实现一个列表,可以在 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 键盘键(以隐藏键盘)时,也会触发 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 方法,这会奇怪地擦除所有项目而不是保持原样.
问题是rangeOfString 部分总是返回 NSNotFound。我不明白为什么,如果我记录两个字符串是正确的变量。
例如:
[@"Angola" rangeOfString @"A"].location 会给 NSNotFound
我再说一遍,这只发生在键盘被隐藏时。有人有想法吗?
提前致谢
【问题讨论】:
-
因此,由于
rangeOfString:实际上不可能有条件地无法正常工作,是时候更仔细地查看参数本身了。 -
Well Logs 并没有告诉我太多,但我重新审查了,那是因为添加的字符是一个新行(“\n”)。
标签: iphone ios keyboard nsstring uitextfield