Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change NSTableView alternate row colors

I'm using the "Alternating Rows" option in Interface Builder to get alternating row colors on an NSTableView. Is there any way to change the colors of the alternating rows?

like image 575
indragie Avatar asked Oct 20 '10 00:10

indragie


People also ask

How do I make rows different colors in tableau?

Go to Format > Shading and configure your alternating colors in the "Row Banding" and "Column Banding" sections. You can adjust the colors as well as how many rows to include before alternating (band size) and at what level in your table the banding should be applied.


3 Answers

If you want to use an undocumented way, make a NSColor category and override _blueAlternatingRowColor like this:

@implementation NSColor (ColorChangingFun)

+(NSColor*)_blueAlternatingRowColor
{
    return [NSColor redColor];
}

@end

or to change both colors, override controlAlternatingRowBackgroundColors to return an array of colors you want alternated.

@implementation NSColor (ColorChangingFun)

+(NSArray*)controlAlternatingRowBackgroundColors
{
    return [NSArray arrayWithObjects:[NSColor redColor], [NSColor greenColor], nil];
}

@end
like image 53
Ken Aspeslagh Avatar answered Oct 30 '22 00:10

Ken Aspeslagh


Found a better way to do it here. That method overrides the highlightSelectionInClipRect: method in an NSTableView subclass so you can use any color you want for the alternating rows. It's not as hackish as using an NSColor category, and it only affects table views you choose.

like image 30
indragie Avatar answered Oct 30 '22 01:10

indragie


I subclassed NSTableView and implemented drawRow:clipRect: like this...

- (void)drawRow:(NSInteger)row clipRect:(NSRect)clipRect
{
    NSColor *color = (row % 2) ? [NSColor redColor] : [NSColor whiteColor];
    [color setFill];
    NSRectFill([self rectOfRow:row]);
    [super drawRow:row clipRect:clipRect];
}

It seems to work, but it's so simple that I'm wondering if I'm missing something.

like image 4
sam Avatar answered Oct 30 '22 01:10

sam