如何在Cocoa应用程序中处理箭头键事件?
看这段代码。我假设这个类是NSView
的子类。
#pragma mark - NSResponder
- (void)keyDown:(NSEvent *)theEvent
{
NSString* const character = [theEvent charactersIgnoringModifiers];
unichar const code = [character characterAtIndex:0];
switch (code)
{
case NSUpArrowFunctionKey:
{
break;
}
case NSDownArrowFunctionKey:
{
break;
}
case NSLeftArrowFunctionKey:
{
[self navigateToPreviousImage];
break;
}
case NSRightArrowFunctionKey:
{
[self navigateToNextImage];
break;
}
}
}
视图应该是第一个接收事件的响应者。也许需要使用以下代码来支持此功能。
#pragma mark - NSResponder
- (BOOL)canBecomeKeyView
{
return YES;
}
- (BOOL)acceptsFirstResponder
{
return YES;
}
要使用这个方法,则该类应该是NSResponder
的子类。请参阅另一个处理不需要子类化NSResponder
的答案。
id keyMonitor;
然后开始监控事件,例如在viewDidLoad中。
keyMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *event) {
unichar character = [[event characters] characterAtIndex:0];
switch (character) {
case NSUpArrowFunctionKey:
NSLog(@"Up");
break;
case NSDownArrowFunctionKey:
NSLog(@"Down");
break;
case NSLeftArrowFunctionKey:
NSLog(@"Left");
break;
case NSRightArrowFunctionKey:
NSLog(@"Right");
break;
default:
break;
}
return event;
}];
当不需要显示器时(假设您已定义它),请将其移除
[NSEvent removeMonitor:keyMonitor];