如何防止NSSearchField使用第一个自动完成列表条目覆盖输入的字符串?

时间:2010-10-20 19:12:03

标签: cocoa macos autocomplete nssearchfield

我正在寻找一种方法来创建一个行为如下的nssearchfield:

  • 文字中的用户类型
  • 根据匹配项显示自动填充下拉列表
  • 搜索字段中的文字自动完成列表中的第一项

关键是,我的字符串匹配搜索文本字段中的任何子字符串和自动完成都不起作用,因为它会覆盖我输入的字符串。事实上,这应该是默认行为,还是我误解了搜索领域的目的? 进一步输入会进一步限制列表,但只有在自动填充下拉列表中选择项目后,该项才会插入到文本字段中。

如果使用nssearchfield无法完成此操作,还有其他选择吗?

1 个答案:

答案 0 :(得分:4)

我自己的解决方案实际上非常简单:只需将搜索字符串本身添加到自动完成的建议列表中。
这是在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;