Search code examples
macoscocoanstableviewnstextfield

NSTextField in NSTableCellView


I have a view based NSTableView with a custom NSTableCellView. This custom NSTableCellView has several labels (NSTextField). The whole UI of the NSTableCellView is built in IB.

The NSTableCellView can be in a normal state and in a selected state. In the normal state all text labels should be black, in the selected state they should be white.

How can I manage this?


Solution

  • Probably the easiest way to accomplish this would be to subclass NSTextField and to override the drawRect: method in your subclass. There you can determine whether the NSTableCellView instance containing your NSTextField instances is currently selected by using this code (which I use with a NSOutlineView, but it should also work with NSTableView):

    BOOL selected = NO;
    id tableView = [[[self superview] superview] superview];
    if ([tableView isKindOfClass:[NSTableView class]]) {
        NSInteger row = [tableView selectedRow];
        if (row != -1) {
            id cellView = [tableView viewAtColumn:0 row:row makeIfNecessary:YES];
            if ([cellView isEqualTo:[self superview]]) selected = YES;
        }
    }
    

    Then draw the view like this:

    if (selected) {
        // set your color here
        // draw [self stringValue] here in [self bounds]
    } else {
        // call [super drawRect]
    }