5

Scenario:

The user is entering a date in an NSDatePicker in its textual form with no stepper (on OS X), and when they hit return on the keyboard, I'd like a message to be sent to the controller.

In an NSTextField, I would just hook the action up in Interface Builder, or set it from code, and when the user hits enter, the action message is sent to the target.

The date picker allows to set an action message and a target, but I can't get the action to fire. When I hit enter in the date picker, the action message does not get called.

Am I doing something wrong, or is there a workaround that I have to use? I would not be adverse to subclassing any of the classes involved, if that is what it takes.

Monolo
  • 18,205
  • 17
  • 69
  • 103

1 Answers1

6

An NSDatePicker will not handle or forward key events triggered by the Return or Enter key.

The solution is to subclass NSDatePicker to get the desired behavior in keyDown:

#import "datePickerClass.h"

@implementation datePickerClass
- (void)keyDown:(NSEvent *)theEvent{
    unsigned short n = [theEvent keyCode];
    if (n == 36 || n == 76) {
       NSLog(@"Return key or Enter key");
        // do your action
        //
    } else { 
        [super keyDown:theEvent];// normal behavior
    }
}
@end

That's it.

Edit : also you can use NSCarriageReturnCharacter and NSEnterCharacter

NSString* const s = [theEvent charactersIgnoringModifiers];
unichar const key = [s characterAtIndex:0];
if (key == NSCarriageReturnCharacter || key == NSEnterCharacter) {
jackjr300
  • 7,111
  • 2
  • 15
  • 25
  • Looks nice and simple. Since Apple somewhere in their docs mention to search for solutions in delegates, formatters or similar before resorting to `keyDown:`, I was hoping there would be another solution, but at least this one is simple. A bit of googling led to Events.h where there are even official constants defined for 36 and 76. The helpful comments in that file mention that 76 for the Enter key is not guaranteed to work on non-ANSI keyboards, so I think I'll just use kVK_Return which is guaranteed to work on all keyboards. – Monolo May 17 '12 at 21:35
  • also you can use **NSCarriageReturnCharacter** and **NSEnterCharacter**, I edit my answer – jackjr300 May 19 '12 at 05:52