2
votes

In a view-based NSTableView, your custom row and cell views (subclasses of NSTableRowView and NSTableCellView) get their backgroundStyle property set, so you know if the background is light or predominantly dark (for the selected, highlighted row).

This even gets passed to immediate subviews.

Now, the default text label of the table cell view reacts correctly to this, so on a dark background, the text is drawn in a suitable light color.

However, an NSTextField added to provide extra text (with a custom text color set in Interface Builder) does not automatically adhere to this convention.

Is there a simple way in the API to get the text field to play nice, or do I have to subclass it?

2
How is it that the default text label of the table cell view works on this?tofutim

2 Answers

5
votes

Instead of overriding drawRect, you could also do this:

- (void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle {
    NSColor *textColor = (backgroundStyle == NSBackgroundStyleDark) ? [NSColor windowBackgroundColor] : [NSColor controlShadowColor];
    self.detailTextField.textColor = textColor;
    [super setBackgroundStyle:backgroundStyle];
}

See also here: http://gentlebytes.com/blog/2011/08/30/view-based-table-views-in-lion-part-1-of-2/

3
votes

Just subclass NSTableCellView then implement drawRect:

- (void)drawRect:(NSRect)dirtyRect
{
    // Drawing code here.
    if (self.backgroundStyle == NSBackgroundStyleDark) {
        [yourTextFieldIVar setTextColor:[NSColor whiteColor]];
    } else if(self.backgroundStyle == NSBackgroundStyleLight) {
        [yourTextFieldIVar setTextColor:[NSColor blackColor]];
    }
}