How to handle arrow key event in Cocoa app?

eonil picture eonil · May 14, 2011 · Viewed 10k times · Source

How to handle arrow key event in Cocoa app?

Answer

eonil picture eonil · May 14, 2011

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.