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.
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) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With