How to get elements inside a selected row in a NSTableView?

Aamir picture Aamir · Oct 11, 2012 · Viewed 13.4k times · Source

I have an NSTableView of content type View Based with two columns.

My objects are structured as follows:

Table View
    Table Column
        Table Cell View
            Text Field
    Table Column
        Table Cell View
            Popup Button

For a selected row, I want to get an element inside the selected row for a specific column. Specifically, I want to get the Text Field in the first column for the selected row.

I have an outlet to the table view and I have the index of the selected row so far, but that's about it:

- (void)getSelectedTextField
{
    NSInteger selected = [tableView selectedRow];
}

Any ideas on how I can go about tackling this problem?

Edit: This is what I am trying to do: I want to change the text field to be in an editing state and focus on it so the user can start editing the text field value as soon as it is selected

Answer

Aamir picture Aamir · Oct 12, 2012

I seemed to have solved my own problem:

- (void)getSelectedTextField
{
    NSInteger selected = [tableView selectedRow];

    // Get row at specified index
    NSTableCellView *selectedRow = [tableView viewAtColumn:0 row:selected makeIfNecessary:YES];

    // Get row's text field
    NSTextField *selectedRowTextField = [selectedRow textField];

    // Focus on text field to make it auto-editable
    [[self window] makeFirstResponder:selectedRowTextField];

    // Set the keyboard carat to the beginning of the text field
    [[selectedRowTextField currentEditor] setSelectedRange:NSMakeRange(0, 0)];
}