How to make round cornered NSTableView rows?

2019-08-03 17:30发布

问题:

I'd like to make something like this (on the new iTunes):

As you can see when the row is selected it's "highlight" state is a round cornered row.
How can I achieve something like this?

回答1:

You need to subclass NSTableview and override -highlightSelectionInClipRect: method.

It can be done like this:

Change your tableView's highlighting mode from regular to Source list in Attributes Inspector:

And now subclass NSTableView like this:

-(void)highlightSelectionInClipRect:(NSRect)theClipRect
{
    NSRange visibleRowIndexes = [self rowsInRect:theClipRect];
    NSIndexSet *selectedRowIndexes = [self selectedRowIndexes];
    NSUInteger endRow = visibleRowIndexes.location + visibleRowIndexes.length;
    NSUInteger row;

    for (row=visibleRowIndexes.location; row<endRow; row++)
    {
        if([selectedRowIndexes containsIndex:row])
        {
            NSRect rowRect = NSInsetRect([self rectOfRow:row], 3, 4);
            NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:rowRect xRadius:4.0 yRadius:4.0];
            [[NSColor colorWithCalibratedRed:0.474 green:0.588 blue:0.743 alpha:1] set];
            [path fill];
        }
    }
}

Result: