0

我创建了一个自定义 UITextField,用于将用户输入与数据库记录进行比较。一切都很好,直到用户在我已经提出建议之后在文本字段中放置一个空格。它使应用程序崩溃并显示以下消息:

由于未捕获的异常“NSRangeException”而终止应用程序,原因:“ * -[__NSCFConstantString substringToIndex:]: Range or index out of bounds”

这是代码:

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;
    }
}

}

4

1 回答 1

0

我想知道你的钥匙是否正确?

UITextField没有selectionRange公开定义的 AFAICT 属性。但是,<UITextInput>-UITextField符合 - 有一个selectedTextRange属性。这可能是你的意图吗?(可能有一个未记录的私有财产实际上被称为selectionRange您不小心遇到的,并且在您遇到的情况下其行为不符合预期。)

或者,您真的是说UITextView- 其中有selectedRange- 但仍然没有selectionRange

On a separate note, I don't think subclassing UITextField is the right approach here. 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.

于 2012-05-14T18:03:49.233 回答