views:

151

answers:

2

How can I navigate through my table view with the arrow keys. Much like setAction: or setDoubleAction, but instead of reacting to clicks, react with the arrow keys moving up or down through the table.

+2  A: 

I'm not sure what you mean because when I select something in a table I can move up and down in the table using the arrow keys. But if you want to customize the behavior more I have a solution. In one of my apps I wanted to detect when the return or enter key was pressed and then perform some action accordingly. I created a new class and made it a subclass of NSWindow. In interface builder I set the main window to be this class. Then I override the keyDown: method of NSWindow in that subclass. So whenever my main window is frontmost (first responder) then key presses are detected and filtered through the method. I'm sure you could do something similar for arrow presses. You might want to make your class a subclass of NSTableView instead of NSWindow depending on how you want to catch the key presses. I wanted it to work for the entire application but you may want it to work only when the table view is first responder.

- (void)keyDown:(NSEvent *)theEvent {
    if ([theEvent type] == NSKeyDown) {
        NSString* characters = [theEvent characters];
        if (([characters length] > 0) && (([characters characterAtIndex:0] == NSCarriageReturnCharacter) || ([characters characterAtIndex:0] == NSEnterCharacter))) {
            // do something here when return or enter is pressed
        }
    }
}
regulus6633
I don't understand why people aren't understanding what I'm asking. All I want to do is use the arrow keys as a replacement for clicking. So if I arrow down to row x it'll do an action much like how `setAction` does for clicking
Matt S.
+2  A: 

In your table view delegate, implement tableView:shouldSelectRow:. Do whatever you want, then return YES. It'll get triggered as you select items in the table view.

Nicholas Riley
works great. Thanks!!!
Matt S.