Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

cocoa - How to prevent NSSearchField from overwriting entered strings using the first autocompletion list entry?

I am looking for a way to create an nssearchfield that behaves as follows:

  • user types in text
  • based on matches an autocompletion drop-down appears
  • the text in the search field does not autocomplete to the first item in the list

The point is, my string matching searches for any substring and autocompletion in the text field would not work because it would overwrite my entered string. In fact it seems this should be the default behaviour, or am I misunderstanding the purpose of a search field?
Typing further would restrict the list further and further, but only after selecting an item in the autocompletion dropdown would that item be inserted into the text field.

If this cannot be accomplished using an nssearchfield, is there an alternative?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My own solution was actually very simple: just add the search string itself to the list of suggestions for the autocompletion.
This is done in the NSSearchField delegate method 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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...