使自动完成不区分大小写

时间:2015-12-13 03:19:36

标签: objective-c macos cocoa

我正在为OSX应用程序实现cocoa中的自动完成功能,到目前为止,我已经将其全部固定下来了。一个问题是自动完成是区分大小写的,而这并不是我想要/需要的。理想情况下,自动完成将是不明智的。相关代码如下:

    @implementation autocompleteController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.textField.delegate = self;
}

-(void)controlTextDidChange:(NSNotification *)obj{
    NSTextView * fieldEditor = [[obj userInfo] objectForKey:@"NSFieldEditor"];
    if (self.isAutocompleting == NO  && !self.backspaceKey) {
        self.isAutocompleting = YES;
        self.lastEntry = [[[fieldEditor string] capitalizedString] copy];
        [fieldEditor complete:nil];
        self.isAutocompleting = NO;
    }
    if (self.backspaceKey) {
        self.backspaceKey = NO;
    }
}

-(NSArray *)control:(NSControl *)control textView:(NSTextView *)textView completions:(NSArray *)words forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger *)index{
    NSMutableArray * suggestions = [NSMutableArray array];
    NSArray * possibleStrings = @[@"TEST", @"ABC", @"abc", @"amauroy", @"AMA", @"amazing"];

    if (!self.lastEntry || !possibleStrings) {
        return nil;
    }
    for (NSString * string in possibleStrings) {
        if ([string hasPrefix:self.lastEntry]) {
            [suggestions addObject:string];
        }
    }
    return suggestions;
}

-(BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector{
    if (commandSelector == @selector(deleteBackward:)) {
        self.backspaceKey = YES;
    }
    return NO;
}

@end

2 个答案:

答案 0 :(得分:3)

正如Pro Blaster指出的那样,问题在于以下几行:

if ([string hasPrefix:self.lastEntry]) {

您的自动填充区分大小写,因为-hasPrefix:区分大小写。一种方法是将所有内容转换为小写(当然,大写也适用)。另一种方法是编写不区分大小写的-hasPrefix:版本,并使用类别将其添加到NSString,如下所示:

@interface NSString (autocomplete)

- (BOOL)hasPrefixIgnoringCase:(NSString*)aString;

@end;

@implementation NSString (autocomplete)

- (BOOL)hasPrefixIgnoringCase:(NSString*)aString
{
    NSRange *prefix = [self rangeOfString:aString options:NSCaseInsensitiveSearch];
    return prefix.location == 0 && prefix.length == aString.length;
}

@end

然后在代码中使用该方法:

if ([string hasPrefixIgnoringCase:self.lastEntry]) {

注意:提供的代码未经测试。这个概念很合理,但您可能会发现一两个语法错误。

答案 1 :(得分:2)

我做过一次。
您可以通过替换:

来实现
for (NSString * string in possibleStrings) {
    if ([string hasPrefix:self.lastEntry]) {
        [suggestions addObject:string];
    }
}
return suggestions

使用:

for (NSString * string in possibleStrings) {
    if ([[string lowercaseString] hasPrefix:[self.lastEntry lowercaseString]]) {
        [suggestions addObject:string];
    }
}
return suggestions;