我正在寻找一种方法来创建一个行为如下的nssearchfield:
关键是,我的字符串匹配搜索文本字段中的任何子字符串和自动完成都不起作用,因为它会覆盖我输入的字符串。事实上,这应该是默认行为,还是我误解了搜索领域的目的? 进一步输入会进一步限制列表,但只有在自动填充下拉列表中选择项目后,该项才会插入到文本字段中。
如果使用nssearchfield无法完成此操作,还有其他选择吗?
答案 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;