NSDatePicker misbehavior
May 14, 2010 Leave a Comment
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.
