iphone - 隐藏键盘时 NSString rangeOfString 问题

标签 iphone ios keyboard nsstring uitextfield

我正在实现一个列表,可以在 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/

相关文章:

iphone - iOS - 以编程方式使用自动布局将 UIView 定位在 super View 的中心

ios - Xcode启动图像问题

iphone - 如何将焦点设置到 iPhone 中的下一个 uitextfield?

python - 如何将按键事件发送到 webkit.WebView() 控件?

javascript - 使用左、右、下、上、主页和结束虚拟按钮的 HTML Texeare 插入符号控件

iphone - UITableViewCell 自动布局

iphone - iOS - 动态按钮

ios - 从 iPhone 加载联系人在 Swift 中崩溃

iOS UIApplication openURL 非常慢

ios - Realm 是否像 SQLite 和 Core Data 一样安全?