开发者

NSTokenField does not let me type other strings than tokenField:completionsForSubstring:... returns

开发者 https://www.devze.com 2023-04-11 20:55 出处:网络
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:index

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 d开发者_高级运维oes 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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消