Search code examples
objective-cnstableview

NSTableView Cell Display Issue


I'm using a view-based NSTableView, and I've ran across a little issue.

I'm trying to switch the text color of my two labels from black to white when highlighted.

To do so, I've written the following code,

- (void)tableViewSelectionDidChange:(NSNotification *)notification
{
    NSView * viewInQuestion = [table viewAtColumn:0 row:[table selectedRow] makeIfNecessary:YES];

    if ([viewInQuestion isNotEqualTo:lastViewSelected])
    {
        [(NSTextField*)lastViewSelected.subviews.lastObject setTextColor:NSColor.blackColor];
        [(NSTextField*)[lastViewSelected.subviews objectAtIndex:1] setTextColor:NSColor.grayColor];
    }

    [(NSTextField*)viewInQuestion.subviews.lastObject setTextColor:NSColor.whiteColor];
    [(NSTextField*)[viewInQuestion.subviews objectAtIndex:1] setTextColor:NSColor.whiteColor];

    lastViewSelected = viewInQuestion;
}

That works great; I get this result:

The issue is that sometimes the text doesn't appear white even though an NSLog told me that the NSTextField's color was NSCalibratedWhite (or whatever it's called).

The color also switches back to black when the textField is not visible (scrolling away from it and then back). Yet again, even when it does this, the NSTextField's color is still logged as white.


Solution

  • Overriding setBackgroundStyle on NSTableViewCell has worked perfectly for me, at least on OS X 10.8. (Given the number of relevant questions here on SO, one can guess that there used to be some problems before.)

    The background style is updated on selection events and on window activation/deactivation, just as one would expect.

    Here's my custom cell impl — as trivial as it can get:

    @implementation RuntimeInstanceCellView
    
    - (void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle {
        [super setBackgroundStyle:backgroundStyle];
        self.detailTextField.textColor = (backgroundStyle == NSBackgroundStyleLight ? [NSColor darkGrayColor] : [NSColor colorWithCalibratedWhite:0.85 alpha:1.0]);
    //    self.detailTextField.textColor = (backgroundStyle == NSBackgroundStyleLight ? [NSColor blackColor] : [NSColor whiteColor]);
    }
    
    @end