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

微笑、不失礼 提交于 2019-12-01 08:30:05

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