Reputation: 399
I am trying to implement a simple NSTextField with autocomplete that behaves more like a JQuery UI autocomplete (http://jqueryui.com/autocomplete/) than the default behavior of NSSearchField. The difference between the two is that with JQuery UI the user has to manually select one of the suggestions before it becomes active in the textfield, whereas with the NS methods the first suggestion is automatically selected.
The reason is that the list of suggestions I will provide to the user are not going to match the text, but instead will be related. For example, if the user types "app", instead of suggesting "apple", I will suggest "fruit". Unfortunately, with the default behavior, if the first item is automatically selected, then the textfield will change to "fruit" as soon as it is suggested, which is not the desired behavior (I want it to stay as "app" until the user selects "fruit" themselves.
Is it possible to prevent the first item from automatically being selected? The closest solution I have found is listed below. While it does prevent the text from being overwritten, I would prefer to not have any item selected at all, since the list is meant to be a list of valid entries, and by showing what the user has typed as the first item, it would incorrectly indicate that the input is always valid. So in other words, I am trying to use the autocomplete to both speed entry as well as restrict the input to valid entries.
Closest solution found so far: How to prevent NSSearchField from overwriting entered strings using the first autocompletion list entry?
Upvotes: 1
Views: 1041
Reputation: 399
I figured this out. First in...
control:textView:completions:forPartialWordRange:indexOfSelectedItem:
I added:
*index = -1;
This tells the autocomplete to not select anything (as described here: NSTextView Class Reference)
index
On input, an integer variable with the default value of 0. On output, you can set this value to an index in the returned array indicating which item should be selected initially. Set the value to -1 to indicate there should not be an initial selection.
Then, the next problem I had was that if you enter more than one word in the search field, then the autocompletion only replaces the last word, whereas the desired behavior is to replace the entire search string. In order to resolve this, I subclassed NSTextView and added the following method:
-(NSRange) rangeForUserCompletion {
return NSMakeRange (0, 1);
}
This makes sure that the entire search string is replaced instead of just the last word.
Upvotes: 1