这看起来很简单,但很重要。
将NSDatePicker(样式:图形)放入窗口,构建&运行,然后尝试使用箭头键移动。唯一的反应就是来自电脑的“叮当”。
我在一个简单的自定义NSDatePicker子类中重写了-keydown
并打印了theEvent,注意到它们有相应的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”键以单步执行对象。
这似乎是一个很大的解决方法。是否还有其他方式已包含在日期选择器中?
答案 0 :(得分:0)
我意识到这个问题真的很老了,但我只是在努力解决这个问题,所以...... 以下方法适合我。
- (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关联的图形日期选择器。自定义textfieldcell通过修改所选日期来处理快捷键(" 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];
}