Blue Bar Effect
One of the interesting visual effects Apple introduced in the first version of iTunes was the alternating stripes of color in the background of the table rows. This coloration helped to visually distinguish rows in a list of potentially thousands of songs. The amazing part is that this very cool effect can be achieved in only four lines of code.
Audience
This article is for developers who are familiar with Cocoa, Project Builder and Interface Builder.
Code
You’ll need to subclass NSTableView in order for the bluebar effect to work correctly. You can either create the subclass manually or use "Subclass ..." menu command in Interface Builder. Once you’ve got your subclass created, open the source file and add the following function:
The AppKit calls
drawRow:clipRect: for each visible row in the table that intersects the clipping rectangle. By overriding this function we get a chance to add our code after the background is drawn but before the cell contents are drawn.We alternate row colors by drawing the background only on odd rows. (Note that since the row index is 0-based, the first odd row (1) will be the second row on the screen.) You could create some very interesting effect by using other algorithms to determine what color to draw on which row. For example, you could create a patriotic table by setting the color to red when
0 == rowIndex % 3, white when 1 == rowIndex % 3 and blue when 2 == rowIndex % 3. We also check to make sure that we don’t draw our special color when the row is selected, since the selection and row rectangles don’t quite match.The last thing we do is to call NSTableView’s version of
drawRow:clipRect: to actually draw the contents of the cells.
One other thing...
When you add an NSTableView to a window in Interface Builder it comes with two columns that have transparent backgrounds. However, if you add additional columns, their backgrounds will be white by default and there’s no standard control to change this behavior. The white background will ruin the blue bar effect if not corrected. The following lines of code added to awakeFromNib in the table subclass takes care of that for us.