Using arrow keys in cocoa?
Asked Answered
A

1

5

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.

Azikiwe answered 16/5, 2011 at 16:50 Comment(3)
Did you add the view to a NSWindow?Scornik
I believe I did, yes. I even set the class to Test, and made the view cover the entire window.Azikiwe
possible duplicate of How to handle arrow key event in Cocoa app?Linehan
F
7

Implement acceptsFirstResponder:

- (BOOL)acceptsFirstResponder
{
    return YES;
}

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

Forecourse answered 16/5, 2011 at 16:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.