我自己的解决方案其实很简单:只需将搜索字符串本身添加到自动完成建议列表中即可。
这在NSSearchField
委托方法control:textView:completions:forPartialWordRange:indexOfSelectedItem:
完成:
...
partialString = [[textView string] substringWithRange:charRange];
...
matches = [NSMutableArray array];
// find any match in our keyword array against what was typed -
for (i=0; i< count; i++)
{
string = [keywords objectAtIndex:i];
if ([string
rangeOfString:partialString
options: NSCaseInsensitiveSearch | NSForcedOrderingSearch
range:NSMakeRange (0, [string length])]
.location != NSNotFound) {
[matches addObject:string];
}
}
[matches sortUsingSelector:@selector(compare:)];
// Make sure we insert the already entered string, even if it does not
// match with any of the retrieved keywords. This will enter this string
// in the search field, as we intended, and it will not be overwritten
// with any match.
[matches insertObject:partialString atIndex: 0];
return matches;
这是相当聪明的,我喜欢它。如果建议有多个词,这会导致问题。它适用于第一个单词,但之后会在第一个单词后插入完整的建议。我想知道有没有办法解决这个问题。 – Jeremy 2011-03-02 05:32:50
回答了我自己的问题。请参阅http://stackoverflow.com/questions/5163646/how-to-make-nssearchfield-send-action-upon-autocompletion/5360535#5360535关于如何在输入空格后避免自动填充的答案。 – Jeremy 2011-03-19 06:20:53
@jeremy你会解释我更多关于你的答案,我想在输入空格后实现相同的自动完成? – 2016-01-05 17:45:45