0

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Robby
  • 23
  • 8

2 Answers2

2

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.

Abcd Efg
  • 2,146
  • 23
  • 41
  • Thank you for the description. This looks for me like very difficult. Do you have a tutorial or an example of a code ? – Robby Aug 16 '15 at 13:37
  • @Robby You are welcome, I edited the answer and added links for sample code and related WWDC session, they explained the code at some point in that session. – Abcd Efg Aug 17 '15 at 11:49
  • Yes ;) I tried the NSComboBox but I think it´s not good for my project because the ComboBox will be to big for my amount of Data. I will try the second way with NSTextField and NSTableView. – Robby Aug 20 '15 at 17:43
  • I subclassed a NSTextField now and created it on my Storyboard. I overrode the method `-(BOOL)becomeFirstResponder`. I wrote in it `[Label setHidden:NO]; NSLog(@"ABC");` It prints "ABC" in the console when I select the NSTextField under which a TableView should appear but it doesn't hide the Label. Why does the code behave like this ? – Robby Sep 11 '15 at 18:42
2

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;
}
ankhzet
  • 2,517
  • 1
  • 24
  • 31