Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using arrow keys in cocoa?

I was doing a little research into this, and I found this question. I implemented the code used there, but nothing happened. Here is the exact code I am using:

.h file

#import <Cocoa/Cocoa.h>


@interface Test : NSView {

}

-(void)keyUp:(NSEvent*)event;
-(void)keyDown:(NSEvent*)event;

@end

.m file

#import "Test.h"


@implementation Test

- (void)keyDown:(NSEvent*)event {
    NSLog(@"A key has been pressed");
    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

What is wrong? Is there something that I have to add to the interface?

EDIT: Well, something actually did happen. I my computer beeped at me. Nothing more.

like image 224
Justin Avatar asked May 16 '11 16:05

Justin


1 Answers

Implement acceptsFirstResponder:

- (BOOL)acceptsFirstResponder
{
    return YES;
}

Also, make sure that your view is first responder (e.g. by clicking inside the view).

like image 90
omz Avatar answered Oct 10 '22 02:10

omz