Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom background in view-based NSTableView

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.

like image 312
indragie Avatar asked Dec 28 '11 22:12

indragie


2 Answers

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

like image 131
Francis McGrew Avatar answered Oct 02 '22 00:10

Francis McGrew


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--;
        }
    }
}
like image 37
Monolo Avatar answered Oct 02 '22 02:10

Monolo