Search code examples
cocoanstextfield

How to change NSTextField text color on row selection?


For cocoa, I have an NSTableView set to be view based. When a row is selected, the text fields change their color to white. How do I keep it black?

I should also note that the Highlight is set to Source List (it does the same thing on Regular). Highlight Setting

Unselected row Unselected

Selected Row Selected Row

I was hoping for something similar to the state config for iOS:

enter image description here

This was suggested in WWDC 2011 Session 120 but it's a bit delayed so I'm not going to use it. It may work for someone else though.

- (void)tableViewSelectionDidChange:(NSNotification *)notification
{
    [tableView enumerateAvailableRowViewsUsingBlock:^(NSTableRowView *rowView, NSInteger row){
        NSTableCellView *cellView = [rowView viewAtColumn:0];
        if(rowView.selected){
            cellView.textField.font = [NSFont boldSystemFontOfSize:14];
        }else{
            cellView.textField.font = [NSFont systemFontOfSize:14];
        }
    }];
}

Solution

  • Depending on why you need to do this, there are 2 approaches.

    You can subclass NSTableRowView and override -[NSTableRowView interiorBackgroundStyle] to return NSBackgroundStyleLight. This will tell the cells that they are on a light background and to draw dark text, which will be black.

    The other way is to subclass NSTableCellView and override -[NSTableCellView setBackgroundStyle:] and set the colors yourself there.