10
votes

I'm using a view-based table view and don't want it to draw NSTextFields with white text color when it is selected. I was not able to find a working solution. So any help is very appreciated.

Here is my problem:

enter image description here

I want the "Selection is white" text also be drawn in the default text color.

So far I figured out that

  • Setting attributes in tableView:viewForTableColumn:item: does not really help
  • Setting NSTextField color to a custom color, which is something different than the control default color, will prevent from drawing in white but it still looses font style (bold, italic, etc).
  • Setting NSTableView's selectionHighlightStyle attribute to NSTableViewSelectionHighlightStyleNone does the trick but it will not redraw NSTableRowView. Also the select style is not what I want. I want the first click to select the row and the second click to edit the text field. When you use NSTableViewSelectionHighlightStyleNone your first click starts editing the text field.
  • The text color does not change if the NSTextField is bordered. But I don't want bordered text fields (As shown in the screenshot. The text fields are editable)

I couldn't figure out 'how' the text field gets the white color. I have overridden setTextColor: and realized that it is never called when selection is changed. So I guess an NSAttributedString is built somewhere inside the NSTableView drawing/selecting routine.

Any help is very much appreciated.

3

3 Answers

14
votes

I found the answer. I had to subclass NSTableCellView and override setBackgroundStyle:. That's all!

- (void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle {
  [super setBackgroundStyle: NSBackgroundStyleLight];
}
0
votes

Instead of overriding NSTableCellView's backgroundStyle, I found it more convenient to override viewWillDraw() in NSTableRowView instead. This is actually the method that by default changes your cell view's background style during selection.

You would disable this behavior by:

class TableViewDelegate: NSObject, NSTableViewDelegate {
    func tableView(tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
        return TableRowView(frame: NSRect.zero)
    }
}

class TableRowView : NSTableRowView {
    private override func viewWillDraw() {
        // By do nothing we prevent the super method to be called. It would otherwise change the selected cell view's backgroundStyle property.
    }
}
-1
votes

I set cell colour in my table view delegate's -tableView:willDisplayCell:forTableColumn:row: method.

-(void)tableView:(NSTableView *)tableView willDisplayCell:(id)cell 
   forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
   if(tableView==<table view id of interest>)
      {
      ...
      [cell setTextColor:<colour appropriate for this cell>];
      ...
      }
   ...
}

This does not affect font size or styling.