6
votes

I have custom alternating row colors in my view-based NSTableView by overriding NSTableRowView's -drawBackgroundInRect:. This works for the most part in that the colors of the cells themselves change, but it obviously does not affect the background of the table view itself (e.g. when the scroll view is bounced). Screenshot:

NSTableView background

What is the best way to customize this? I posted a question earlier about this very same problem but with cell based table views. The solution I found does not seem to work with view-based table views.

3
Do you want the background to be alternated too?lbrndnr
Yes, with the same colors I'm using for the cellsindragie
Why don't you try to replicate the empty rows in drawBackgroundInClipRect? NSTableView is drawing it in this method too and it doesn't seem to hard.lbrndnr

3 Answers

3
votes

Have you tried overriding NSTableView's drawBackgroundInClipRect:(NSRect)clipRect

2
votes

There is a video of the talk "View Based NSTableView Basic to Advanced" (available here) in which the background below the last line is drawn.

In order to extend that technique, you can create a subclass of NSTableView and add a little code:

// somewhere in your setup code (colors just intended as examples):

tableView.colors = [NSArray arrayWithObjects: [NSColor lightGrayColor],[NSColor grayColor], nil]; 


// In the table view subclass:

-(void)drawBackgroundInClipRect:(NSRect)clipRect
{
    // The super class implementation obviously does something more
    // than just drawing the striped background, because
    // if you leave this out it looks funny
    [super drawBackgroundInClipRect:clipRect];

    NSRect boundsToDraw = clipRect;

    CGFloat   yStart   = 0;
    NSInteger rowIndex = -1;

    if ( clipRect.origin.y < 0 ) {        

        while (yStart > NSMinY(boundsToDraw)) {

            CGFloat yRowTop = yStart - self.rowHeight;

            NSRect rowFrame = NSMakeRect(0, yRowTop, boundsToDraw.size.width, self.rowHeight);

            NSUInteger colorIndex = rowIndex % self.colors.count;

            NSColor *color = [self.colors objectAtIndex:colorIndex];

            [color set];

            NSRectFill(rowFrame);

            yStart -= self.rowHeight;

            rowIndex--;
        }
    }
}
-1
votes

I didn't try it but what happens if you just override -drawRect: ?