Search code examples
swiftcocoanstableviewnstextfield

Select next row when Enter is pressed while editing a NSTextField inside a NSTableView


I set some NSTextFields inside my view-based NSTableView to be editable, and to send an action on "end editing" (so when Enter or Tab is pressed, or when the focus is lost). The behavior when hitting Tab is perfect: the cell on the right of the current one gets selected and is ready to be edited. Same goes for Shift+Tab. When hitting Enter, the field is "deactivated" but the same row stays selected, which is the normal behavior. What I want to achieve is a vertical version of what Tab does, with the Enter key.

To be clear: I'm editing a NSTextField inside my table. I hit Enter. I want the next row to become selected, and the field in the same column that I was editing previously should become "activated" (meaning it turns into an editable NSTextField with its current content highlighted). The action should still be triggered normally, like it would if you hit Tab while editing a cell.

Is that possible? If yes, how would I proceed?

I thought about subclassing NSTextField and playing with keyDown a little, but I think I would then have to use the notification center to trigger a callback that would make the row selection change in my table and the activation of the next table cell. This seems like overkill, and I wouldn't know how to make the latter happen (activate the NSTextField for editing).

Thanks!


Solution

  • I would use the NSControlTextEditingDelegate method

    - (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)command
    

    with the text field to detect the enter key and

    - (void)editColumn:(NSInteger)columnIndex row:(NSInteger)rowIndex withEvent:(NSEvent *)theEvent select:(BOOL)flag
    

    to select the next row in the table view.