My issue is that NSTokenField does not allow me to type any text I want, it's only allow me to type strings that are included in the NSArray that tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem: returns.
- (NSArray *)tokenField:(NSTokenField *)tokenField completionsForSubstring:(NSString *)substring indexOfToken:(NSInteger)tokenIndex indexOfSelectedItem:(NSInteger *)selectedIndex {
return [NSArray arrayWithObjects:@"AA", @"BB", @"CC", @"DD", nil];
}
My NSTokenField can only contain the above text-tokens.
If I type for example XXX it does not appeared and it cannot be added.
Why this happens since the documentation mentions "The user could enter a string that is not in the list of possible completions and that is also tokenized."
What am I missing ?
The default value for selectedItemIndex is 0 — the first item in your return list.
So you either need to set this to -1 in the case that substring isn't represented in your list (otherwise it will replace the text the user typed with the text of your first completion)
or
Only return things in the completion list which actually math the prefix the user typed. (This is often the correct user experience.)
- (NSArray *)tokenField:(NSTokenField *)tokenField completionsForSubstring:(NSString *)substring indexOfToken:(NSInteger)tokenIndex indexOfSelectedItem:(NSInteger *)selectedIndex
{
NSArray *completions = [NSArray arrayWithObjects:@"AA", @"BB", @"CC", @"DD", nil];
NSMutableArray *filteredCompletions = [NSMutableArray array];
[completions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([[obj lowercaseString] hasPrefix:[substring lowercaseString]])
[filteredCompletions addObject:obj];
}];
return filteredCompletions;
}