views:

86

answers:

3

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?

+1  A: 

There is no settable property for this, however you can respond to the delegate method -tableView:willDisplayCell:forTableColumn:row: and set the cell's background color based on the evenness of the row number.

Joshua Nozzi
This doesn't seem to work when there are no cells in the table view (doesn't change the background of the table view itself)
macatomy
A: 

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
Ken Aspeslagh
Why hack when the API gives you a way?
Joshua Nozzi
um, because it's fun ;) ROFL
Ken Aspeslagh
This works, but it only changes one of the colors.
macatomy
You want to change the white color too? What are you doing this for exactly?
Ken Aspeslagh
Why would someone down-vote my answer?
Ken Aspeslagh
Edited to show how to change both colors.
Ken Aspeslagh
@Ken I think its a fairly common practice to customize the table view cell colors, surprised that NSTableView doesn't support this by default. The controlAlternatingRowBackgroundColors method worked great, I think its the only way to do this.
macatomy
The only down-side is that it will affect all such tableviews in the app.
Ken Aspeslagh
+1  A: 

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.

macatomy
+100 I came across this question a few days ago hoping for a good answer, but didn't find a satisfactory one. Thankfully, I happened to see it come up again! Thanks!
Dave DeLong