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

岁酱吖の 提交于 2019-12-19 09:58:08

问题


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 ?


回答1:


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;
}


来源:https://stackoverflow.com/questions/7697584/nstokenfield-does-not-let-me-type-other-strings-than-tokenfieldcompletionsforsu

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