Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDatePicker action method not firing

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.

like image 729
Monolo Avatar asked May 14 '12 20:05

Monolo


1 Answers

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) {
like image 124
jackjr300 Avatar answered Oct 19 '22 23:10

jackjr300