Robby
Robby

Reputation: 23

NSTextField Autocomplete / Suggestions

Since some days I am trying to code an autocompletion for a NSTextField. The autocompletion should look that way, that when the user clicks on the NSTextfield a list should be displayed under the TextField which possibilities are available. After typing one letter or number the list should refresh with the possibilities.

The suggestions in this list should come from an NSMutableArrayor a NSMutableDictionary

This autocomplete / autosuggestion method should be for a MAC application.

Upvotes: 0

Views: 2064

Answers (2)

Abcd Efg
Abcd Efg

Reputation: 2146

You can use NSComboBox for that matter. You also need to set its Autocompletes attribute in IB or [comboBox setCompletes:YES] in code. Keep in mind that it is case-sensitive.

However if you need it to be done in the exact way that you described, you need to make the list by subclassing NSWindowController and NSTableView and change them to look like a list or menu to show under you NSTextField. Set the NSTextField's delegate and do the search and list update on text changes.

Avoid the NSMenu in this case as it will take away the focus from the text field while you are typing.

Apple addressed it in WWDC 2010 Session 145. They explained about a text field with suggestions menu and how to get it to work. They also provide the sample codes in their website.

You can find the sample code here.

Upvotes: 2

ankhzet
ankhzet

Reputation: 2570

Just adding to @AbcdEfg's answer, to make NSComboBox case-insensitive, you can subclass it and override it's [completedString:] method like this:

- (NSString *) completedString:(NSString *)string {
  NSUInteger l = [string length];
  if (!!l)
    for (NSString *match in [self objectValues])
      if ([[match commonPrefixWithString:string options:NSCaseInsensitiveSearch] length] == l)
        return [match stringByReplacingCharactersInRange:NSMakeRange(0, l) withString:string];

  return nil;
}

Upvotes: 2

Related Questions