简体   繁体   中英

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

I set some NSTextField s 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!

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.

There are two steps that you need to kill your problem.

  1. Trigger when return button is pressed. You can use textFieldShouldReturn method of UITextFieldDelegate to finish this step.
  2. Inside the method that you used at step 1, select next row in your tableView.

    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section]; [self.tableView selectRowAtIndexPath: nextIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone]; [self tableView:self.tableView didSelectRowAtIndexPath: nextIndexPath];

Hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM