Search code examples
macosswift5nscombobox

How to handle backspace in NSComboBox with swift 5


I have NSComboBox with external datadource and I'm using method:

(NSString *)comboBox:(NSComboBox *)aComboBox completedString:(NSString *)string

to complete string with suggestions, everything is working all right except when I press backspace, it won't autocomplete. I have tried to debug and it didn't even call this method on backspace. I have also tried call it directly from method:

-(void)controlTextDidChange:(NSNotification *)notification

but it wont select completed string that way. My question is what am I doing wrong? Is there better way to handle delete or I should just try to select completed text programmatically?


Solution

  • Use controlTextDidChange to detect when backspace was pressed, then trigger completion manually using complete on NSTextView:

    -(void)controlTextDidChange:(NSNotification *)notification {
        if (... /* backspace pressed */) {
            NSTextField *textField = [[notification userInfo] objectForKey:@"NSFieldEditor"];
            [textField complete:self];
        }
    }