NSDatePicker misbehavior

NSDatePicker does not behave as it should with respect to keyboard events. Specifically, an NSDatePicker will not handle or forward key events triggered by the Return or Enter key. This becomes an issue if you have a window with a default button. The proper behavior would have the button’s action triggered whenever Return or Enter are pressed.

One possible solution is to subclass NSDatePicker to get the desired behavior in keyDown:.

#define RETURN_KEY_CODE 36
#define ENTER_KEY_CODE 76

@implementation MJTDatePicker

- (void)keyDown:(NSEvent *)theEvent {
	unsigned short keyCode = [theEvent keyCode];
	// forward return key and enter key events to the next responder
	if (keyCode == RETURN_KEY_CODE || keyCode == ENTER_KEY_CODE) {
		[[self nextResponder] keyDown:theEvent];
	} else {
		[super keyDown:theEvent];
	}
}

@end

Here’s a sample project that demonstrates the problem and the solution.

Advertisement

About Tony Ingraldi
Majesty Software was founded in 2007 by Tony Ingraldi where he spends his time as a consultant and an independent software developer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.