Change NSTableView alternate row colors

前端 未结 9 1319

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 row

9条回答
  •  遥遥无期
    2020-12-28 17:48

    If you wish to set a custom color paired with the data in each row, I found this way of doing so, thanks to the posts here above, and this solution is also working to implement a custom alternate row color ( except for the empty rows ) :

    create a subclass of NSTableView :

    ColoredRowTableView.h

       @protocol ColoredRowTableViewDelegate 
       -(NSColor *)colorForRow:(NSInteger)row;
       @end
       @interface ColoredRowTableView : NSTableView
       @end
    

    in ColoredRowTableView.m

    - (void)drawRow:(NSInteger)row clipRect:(NSRect)clipRect
    {
        if (row == [self selectedRow])
        {
            [super drawRow:row clipRect:clipRect];
             return;
        }
        NSColor *color = [(id)[self delegate] colorForRow:row];
        [color setFill];
        NSRectFill([self rectOfRow:row]);
        [super drawRow:row clipRect:clipRect];
    }
    

    then in your table view delegate :

    #import "ColoredRowTableView.h"
    @interface MyTableViewDelegate : NSViewController 
    // instead of 
    

    implement the colorForRow: method in your delegate. If the goal is only to provide alternate row it can return a color based on the row number, if it is even or odd. Also don't forget to change the class of your table view to ColoredRowTableView in interface builder

提交回复
热议问题