This seems simple, but essential.
Place an NSDatePicker (style: graphical) into a window, build & run, then attempt to use arrow keys to move around. The only response is a 'ding' from the computer.
I've overridden -keydown
in a simple custom NSDatePicker subclass and printed theEvent to notice they have corresponding keyCodes of 123 through 126.
Then, I stumbled upon resetting the date picker's date after each arrow button press, inside -keydown
, like so:
- (void)keyDown:(NSEvent *)theEvent
switch ([[theEvent valueForKey:@"keyCode"] integerValue]) {
case 126:
// Take away one week from the date
self.dateValue = [NSDate dateWithTimeInterval:-604800 sinceDate:self.dateValue];
break;
.... similar for 125 - 123 ...
}
}
Implementing this method has the side effect of taking away the 'tab' key for stepping through objects.
This seems like a big work-around. Is there another way already included in the date picker??
I realize this question is really old, but I was just working on this, so... The below approach works for me.
- (void)keyDown:(NSEvent *)theEvent
{
NSString* replacementKey = nil;
switch ([theEvent keyCode])
{
case 123: // Left arrow
replacementKey = @"-";
break;
case 124: // Right arrow
replacementKey = @"+";
break;
case 125: // Down arrow
replacementKey = @"]";
break;
case 126: // Up arrow
replacementKey = @"[";
break;
case 53: // esc
case 36: // return -- don't assign replacement key and these will dismiss date picker
break;
default:
replacementKey = [theEvent charactersIgnoringModifiers];
break;
}
if (replacementKey) // 'letter' based shortcut keys
{
[self.textFieldCell dateShortcut:replacementKey];
[self updateGraphicalCalendar];
}
else
{
[self.textFieldCell hidegraphicCalendar];
}
}
Note this is for a graphical date picker associated with a custom NSTextFieldCell. The custom textfieldcell handles the shortcut keys (the "replacementKey") by modifying the selected date, like:
if (NSOrderedSame == [shortcut caseInsensitiveCompare:@"+"] || NSOrderedSame == [shortcut caseInsensitiveCompare:@"="]) // '=' is unshifted '+'
{
emptyComponents.day = 1;
currentDateValue = [calendar dateByAddingComponents:emptyComponents toDate:currentDateValue options:0];
}
else if (NSOrderedSame == [shortcut caseInsensitiveCompare:@"-"])
{
emptyComponents.day = -1;
currentDateValue = [calendar dateByAddingComponents:emptyComponents toDate:currentDateValue options:0];
}
else if (NSOrderedSame == [shortcut caseInsensitiveCompare:@"["]) // same day in previous week
{
emptyComponents.day = -7;
currentDateValue = [calendar dateByAddingComponents:emptyComponents toDate:currentDateValue options:0];
}
else if (NSOrderedSame == [shortcut caseInsensitiveCompare:@"]"]) // same day in next week
{
emptyComponents.day = 7;
currentDateValue = [calendar dateByAddingComponents:emptyComponents toDate:currentDateValue options:0];
}