Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coloring rows in View based NSTableview

I have a view based nstableview. I want to color entire row based on some condtion for which I have used code below

- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row 
{
    NSTableRowView *view = [[NSTableRowView alloc] initWithFrame:NSMakeRect(1, 1, 100, 50)];

    [view setBackgroundColor:[NSColor redColor]];
    return view;;
}

The delegate method is called, but table doesn't seem to be using NSTableRowView returned by delegate method.

Main aim here is coloring entire row based on some condition. Whats wrong in above implementation?

like image 820
sach Avatar asked Jun 06 '12 08:06

sach


Video Answer


1 Answers

For anyone else who hits this and wants a custom NSTableRowView backgroundColor, there are two approaches.

  1. If you don't need custom drawing, simply set rowView.backgroundColor in - (void)tableView:(NSTableView *)tableView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row in your NSTableViewDelegate.

    Example:

    - (void)tableView:(NSTableView *)tableView
        didAddRowView:(NSTableRowView *)rowView
               forRow:(NSInteger)row {
    
        rowView.backgroundColor = [NSColor redColor];
    
    }
    
  2. If you do need custom drawing, create your own NSTableRowView subclass with desired drawRect. Then, implement the following in NSTableViewDelegate:

    Example:

    - (NSTableRowView *)tableView:(NSTableView *)tableView
                    rowViewForRow:(NSInteger)row {
        static NSString* const kRowIdentifier = @"RowView";
        MyRowViewSubclass* rowView = [tableView makeViewWithIdentifier:kRowIdentifier owner:self];
        if (!rowView) {
            // Size doesn't matter, the table will set it
            rowView = [[[MyRowViewSubclass alloc] initWithFrame:NSZeroRect] autorelease];
    
            // This seemingly magical line enables your view to be found
            // next time "makeViewWithIdentifier" is called.
            rowView.identifier = kRowIdentifier; 
        }
    
        // Can customize properties here. Note that customizing
        // 'backgroundColor' isn't going to work at this point since the table
        // will reset it later. Use 'didAddRow' to customize if desired.
    
        return rowView;
    }
    
like image 73
DPlusV Avatar answered Sep 19 '22 05:09

DPlusV