Search code examples
xcodemacoscocoanstableviewnsmenu

NSTableCellView setEditable


I'm using a menu item to set the column text field to editable. This is what I tried, but there is simply no response (no text is turned editable). (I have logged, and the method is called, and the textfield is not null.)

- (IBAction)setEditable:(id)sender
{
    NSInteger selectedRow = [_tableView selectedRow];
    NSInteger selectedColumn = [_tableView selectedColumn];

    NSTableCellView *selectedCell = [_tableView viewAtColumn:selectedColumn row:selectedRow makeIfNecessary:NO];

    [selectedCell.textField setEditable:YES];
}

Does this have to be done in another way? The textfield is also set as editable in IB, so it works by double clicking on it, but I also want the option in the context menu.


Solution

  • A text field is "editable" if it's possible to edit it, that is give it focus. -setEditable: does not initiate editing, which is what you seem to think given that you expect the above code to do the same as double-clicking the field. It just sets a flag on the text field that governs what the text field allows to be done. You can check the flag with -isEditable.

    If you want to initiate editing, you should make the text field the window's first responder using:

    if ([selectedCell.textField acceptsFirstResponder])
        [_tableView.window makeFirstResponder:selectedCell.textField];
    

    If your action method may be invoked when the window is not key, you may want to also do [_tableView.window makeKeyAndOrderFront:self] first.