我自己的解決方案其實很簡單:只需將搜索字符串本身添加到自動完成建議列表中即可。
這在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