这看起来很简单,但很重要。
将NSDatePicker(样式:图形化)放入窗口中,构建&跑步,然后尝试使用箭头键四处移动。唯一的响应是来自计算机的"丁"。
我在一个简单的自定义NSDatePicker子类中重写了-keydown
,并打印了Event,以注意到它们有123到126的相应keyCodes。
然后,我偶然发现在-keydown
内每次按下箭头按钮后都会重置日期选择器的日期,就像这样:
- (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 ...
}
}
实现此方法的副作用是去掉了遍历对象的"tab"键。
这似乎是一个大问题。日期选择器中是否已包含其他方式??
我意识到这个问题很老了,但我只是在研究这个问题,所以。。。以下方法对我有效。
- (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];
}
}
请注意,这是针对与自定义NSTextFieldCell关联的图形日期选择器。自定义文本字段单元格通过修改所选日期来处理快捷键("replacementKey"),如:
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];
}