Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle arrow key event in Cocoa app?

How to handle arrow key event in Cocoa app?

like image 346
eonil Avatar asked May 14 '11 06:05

eonil


People also ask

How do arrow keys work?

To use the arrow keys to move between cells, you must turn SCROLL LOCK off. To do that, press the Scroll Lock key (labeled as ScrLk) on your keyboard. If your keyboard doesn't include this key, you can turn off SCROLL LOCK by using the On-Screen Keyboard.


2 Answers

See this code. I assumed the class is subclass of 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;
        }
    }
}

A view should be a first responder to receive events. Maybe this code will be required to support that.

#pragma mark    -   NSResponder
- (BOOL)canBecomeKeyView
{
    return  YES;
}
- (BOOL)acceptsFirstResponder
{
    return  YES;
}

To use this method, the class should be subclass of NSResponder. See the other answer handling without subclassing NSResponder.

like image 76
eonil Avatar answered Oct 27 '22 05:10

eonil


In my case I wanted a presented NSViewController subclass to be able to listen to arrow key events for navigation with minimal effort. Here's the best solution I've found, a slight variation of Josh Caswell's answer.

Define an event monitor (optional), can be locally in your NSViewController subclass .m

id keyMonitor;

Then start monitoring events, for example in 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;
}];

To remove the monitor when not required (assuming you defined it)

[NSEvent removeMonitor:keyMonitor];
like image 31
Daniel Nordh Avatar answered Oct 27 '22 07:10

Daniel Nordh