Autocomplete with twitter usernames in text field (cocoa)

。_饼干妹妹 提交于 2019-12-03 09:08:55

The most basic implementation involves overriding this method... Definitely not optimal, but you should get the idea:

- (NSArray *) completionsForPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger *)index {
    // this would be defined somewhere else, but just for example.. 
    NSArray *usernames = [NSArray arrayWithObjects:@"@andreas", @"@clara", @"@jeena", @"@peter"];

    NSMutableArray *matchedNames = [NSMutableArray array];
    NSString *toMatch = [[self string] substringWithRange:charRange];
    for(NSString *username in usernames) {
        [matchedNames addObject:username];
    }

    return matchedNames; // that's it. 
}

Once you start having a lot of data, you'll need to employ strategies to pre-do your searches by storing words into hashes with the partial pieces of text in them (like, "Hello" would be put into 4 different arrays stuff into NSDictionary keys for "H", "He", "Hel", "Hell" .. Repeat with every word in your Lexicon. Much quicker that way.

If you want to support auto-complete, just call the 'complete:' method when you detect text is changing in your control.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!