我正在攻击一个简单的Cocoa应用程序,以便像电子游戏一样让屏幕在屏幕上移动.我需要检测按键,但我不会像对话框那样有文本输入字段.
如何在没有文本控件的情况下获得按键操作?特别是,我需要获得箭头键.
在游戏视图中,定义keyUp和keyDown方法:
@interface MyView : NSView -(void)keyUp:(NSEvent*)event; -(void)keyDown:(NSEvent*)event; @end @implementation MyView -(void)keyUp:(NSEvent*)event { NSLog(@"Key released: %@", event); } -(void)keyDown:(NSEvent*)event { // I added these based on the addition to your question :) switch( [event keyCode] ) { case 126: // up arrow case 125: // down arrow case 124: // right arrow case 123: // left arrow NSLog(@"Arrow key pressed!"); break; default: NSLog(@"Key pressed: %@", event); break; } } @end
有关详细信息,请参阅NSView和NSEvent的文档.请注意,keyDown和keyUp事件实际上是在NSResponder(NSView的超类)上定义的.