简体   繁体   English

自动填充UITextField使应用程序崩溃

[英]Autocompleting UITextField crashes app

I have created a custom UITextField that compares user input against database records. 我创建了一个自定义UITextField,用于将用户输入与数据库记录进行比较。 Everything works great until the user puts a space in the text field after I have already suggested something. 在我已经提出了一些建议之后,一切都很好,直到用户在文本字段中输入空格为止。 It crashes the app with the following message: 它使用以下消息使应用程序崩溃:

Terminating app due to uncaught exception 'NSRangeException', reason: ' * -[__NSCFConstantString substringToIndex:]: Range or index out of bounds' 由于未捕获的异常“ NSRangeException”而终止应用程序,原因:“ * -[__ NSCFConstantString substringToIndex:]:范围或索引超出范围”

Here is the code: 这是代码:

NSRange cursorRange = [[self valueForKey:@"selectionRange"] rangeValue];
NSString *entered = [self.text substringToIndex:cursorRange.location];
if (![self.text isEqualToString:entered]) {
    self.text = entered;
    return;
}

NSString *suggestedSuffix;
for (NSString *name in filterData) {
    if (name.length > cursorRange.location && [[name lowercaseString] hasPrefix:entered]) {
        suggestedSuffix = [name substringFromIndex:cursorRange.location];
        NSMutableString *suggestedString = [[NSMutableString alloc] initWithString:entered];
        [suggestedString appendString:suggestedSuffix];
        self.text = suggestedString;
        [self setValue:[NSValue valueWithRange:cursorRange] forKey:@"selectionRange"];
        return;
    }
}

} }

I'm wondering whether you have your key correct? 我想知道您的密钥是否正确?

UITextField does not have a selectionRange property publicly defined AFAICT. UITextField没有公共定义的AFAICT的selectionRange属性。 However, <UITextInput> - to which UITextField conforms - has a selectedTextRange property. 但是, UITextField符合的<UITextInput>具有selectedTextRange属性。 Is this perhaps what you intended? 这也许是您想要的吗? (It's possible there's an undocumented private property actually called selectionRange that you've accidentally encountered, and which doesn't behave as expected in cases such as you encountered.) (您可能偶然遇到了一个未记录的私有属性,实际上称为selectionRange ,在遇到这种情况时,它的行为可能不符合预期。)

Alternatively, did you really mean UITextView - which has a selectedRange - but still no selectionRange ? 另外,您真的是说UITextView具有selectedRange但仍然没有selectionRange吗?

On a separate note, I don't think subclassing UITextField is the right approach here. 另外,我认为在这里UITextField不是正确的方法。 Autocompletion can be completely (no pun intended) implemented using the <UITextFieldDelegate> methods and it is a maxim of Cocoa programming that when you can accomplish a goal through class composition rather than subclassing, you should opt for composition every time. 可以使用<UITextFieldDelegate>方法完全实现自动补全(无双关语),这是Cocoa编程的原则,当您可以通过类组合而不是子类实现目标时,您应该每次都选择组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM