3

I have a single line NSTextField with autocomplete. I want to type some text and have it processed on pressing return. It mostly works fine except it doesn't quite do what I want if I don't want any of the autocomplete suggestions.

In that case I type something in and the first time I press return it dismisses the autocomplete drop down. It takes a second return key press to finish the edit and have the text processed. I would prefer it if it only required a single return key press to dismiss the drop down and process the text.

It looks like the drop down is swallowing the return key press. The field editor's keyDown: and insertText: methods see alphanumeric key events when the drop down is displayed, but don't register the first return key press which dismisses the drop down. They do register return key presses after the drop down has been dismissed.

Any ideas how I can avoid the need for two return key hits?

EDIT: Added some code:

#import "JWAppDelegate.h"

@interface JWAppDelegate()
@property (readwrite, strong) IBOutlet NSTextField *inputTextField;
@property (readwrite, strong) IBOutlet NSTextField *outputTextField;
@end

@implementation JWAppDelegate


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [self.inputTextField setDelegate:self];
}

- (IBAction)textUpdated:(id)sender
{
    [self.outputTextField setStringValue:[@"User typed: " stringByAppendingString:[sender stringValue]]];
}

#pragma mark NSTextFieldDelegate
- (NSArray *)control:(NSControl *)control textView:(NSTextView *)textView completions:(NSArray *)words forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger *)index
{
    // Select nothing in the autocomplete list.
    *index = -1;
    return @[@"foobar", @"foobaz", @"fooqaz"];
}

@end

The nib file has an input text field and a readonly output text field. Type 'hello' into the input without hitting return. Press Esc to bring up the autocomplete options. Now press return without selecting an autocomplete option. I want textUpdated: to get called at this point, but it requires a further press of the return key for this to happen.

4

0 回答 0