Search code examples
macoscocoacolorsnstableviewhighlight

Cocoa osx NSTableview change row highlight color


In my application I have a view based NSTableView with one column. The highlight color of the rows is set to regular (blue). I need to change that color to my custom color. In the interface builder I tried changing it but the only options are "None, regular and source list".

I tried this post solution with no success: https://stackoverflow.com/a/9594543/3065901

I read that I have to use this delegate method but I dont know how to use this.

- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row

I tried drawing the row in that method but i get invalid context warnings and the row still keeps with the same higlight. Please post a simple example of how to use this delegate method:

Need help please. Thanks in advance.


Solution

  • From this link.

    MyNSTableRowView.h

    #import <Cocoa/Cocoa.h>
    @interface MyNSTableRowView : NSTableRowView
    @end
    

    MyNSTableRowView.m

    #import "MyNSTableRowView.h"
    
    @implementation MyNSTableRowView
    - (id)init
    {
        if (!(self = [super init])) return nil;
        return self;
    }
    
    - (void)drawSelectionInRect:(NSRect)dirtyRect {
         if (self.selectionHighlightStyle !=    NSTableViewSelectionHighlightStyleNone) {
         NSRect selectionRect = NSInsetRect(self.bounds, 2.5, 2.5);
         [[NSColor colorWithCalibratedWhite:.65 alpha:1.0] setStroke];
         [[NSColor colorWithCalibratedWhite:.82 alpha:1.0] setFill];
         NSBezierPath *selectionPath = [NSBezierPath bezierPathWithRoundedRect:selectionRect
                                                                   xRadius:6 yRadius:6];
         [selectionPath fill];
         [selectionPath stroke];
         }
    }
    @end
    

    AppDelegate.m

    - (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row
    {         
         MyNSTableRowView *rowView = [[MyNSTableRowView alloc]init];
         return rowView;
    }