简体   繁体   中英

Change background of NSCell without changing all cells in the NSTableColumn

I'm trying to change the background of a specific cell in a cell-based NSTableView . However, when I try to change the background color of just one cell, it affects the entire column. Is there a way to separate whatever binding there must be between the cells and the column?

Here's the code I'm using (with comments explaining what I believe is happening):

// This allows me to change the background of the cell.

[[[[_tableController1 registerTableView] tableColumnWithIdentifier:@"offset"] dataCellForRow:table1idx] setDrawsBackground:YES];

// This gets the cell within the given table column and row.

[[[[_tableController1 registerTableView] tableColumnWithIdentifier:@"offset"] dataCellForRow:table1idx] setBackgroundColor:[NSColor redColor]];        

// This reloads the table so my changes can be visible.

[[_tableController1 registerTableView] reloadData];

A cell-based table uses a single cell per column. It's like a rubber stamp of sorts. It goes down the visible rows, sets up the cell for that row, tells it to draw in the frame rect for that row+column, and then goes to the next row.

You should set a delegate for your table and have it implement -tableView:willDisplayCell:forTableColumn:row: . In that method, set up the attributes for the cell as appropriate for the row. You can't just set an attribute for whatever rows you consider "special". If you change an attribute for some rows, you need to change it to whatever you consider "normal" for all of the other rows, too.

So, your method might look like:

- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
    if ([[atTableColumn identifier] isEqualToString:@"offset"])
    {
        if (rowShouldHaveRedBackground)
        {
            [aCell setDrawsBackground:YES];
            [aCell setBackgroundColor:[NSColor redColor]];
        }
        else
            [aCell setDrawsBackground:NO];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM