質問

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) {
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top