我正在寻找一种方法来创建一个行为如下的 nssearchfield:
- 用户输入文本
- 根据匹配出现自动完成下拉菜单
- 搜索字段中的文本不会自动填充到列表中的第一项
关键是,我的字符串匹配搜索任何子字符串和文本字段中的自动完成将不起作用,因为它会覆盖我输入的字符串。事实上,这似乎应该是默认行为,还是我误解了搜索字段的目的?
进一步键入会进一步限制列表,但只有在自动完成下拉列表中选择了一个项目后,该项目才会插入到文本字段中。
如果这不能使用 nssearchfield 完成,是否有替代方法?
我正在寻找一种方法来创建一个行为如下的 nssearchfield:
关键是,我的字符串匹配搜索任何子字符串和文本字段中的自动完成将不起作用,因为它会覆盖我输入的字符串。事实上,这似乎应该是默认行为,还是我误解了搜索字段的目的?
进一步键入会进一步限制列表,但只有在自动完成下拉列表中选择了一个项目后,该项目才会插入到文本字段中。
如果这不能使用 nssearchfield 完成,是否有替代方法?
我自己的解决方案实际上非常简单:只需将搜索字符串本身添加到自动完成的建议列表中即可。
这是在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;