Autocomplete with twitter usernames in text box (cocoa)

I looked at NSTokenField, NSTextField and NSTextView without any problems:

I am writing a Twtitter client, and when you want to twitter a new tweet, you start writing in a text box, for example:

Going to make coffee, @pe

When you start writing @ , I would like to help the user autofill the username, for example @peter . I have an NSArray with usernames such as:

NSArray *usernames = [NSArray arrayWithObjects:@"@andreas", @"@clara", @"@jeena", @"@peter"]

What should I do to enable simple autocomplete? I would be happy if you had to press F5 or something else for starters. The problem I am facing is that with NSTokenField I don’t know how I should tokenize the string, and NSTextField only works when I write @username at the beginning of the tweet, and NSTextView seems really complicated and too big for such simple thing.

+4
source share
1 answer

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 it. } 

As soon as you start to have a lot of data, you will need to use strategies for preliminary searches, storing words in hashes with partial text fragments (for example, "Hello" will be placed in 4 different arrays in the NSDictionary keys for "H", "He", " Hel "," Hell ". Repeat all the words in your dictionary.

If you want to support automatic completion, just call the "complete:" method when you find that the text is changing in your control.

+3
source

All Articles