NSTableView custom highlight color with NSTableRowView

Getting the right color when you select NSTableView’s row was frustrating for me since I didn’t know how to do it properly. But it is really simple, all you need to do is having a class inherit from NSTableRowView and override its method drawSelection(in dirtyRect: NSRect).

import Foundation
import Cocoa

class MenuTableRowView: NSTableRowView {

    override func drawSelection(in dirtyRect: NSRect) {
        if self.selectionHighlightStyle != .none {
            let selectionRect = NSInsetRect(self.bounds, 2.5, 2.5)
            
            if let color = NSColor.init(named: NSColor.Name("menu_table_selection_color")) {
                color.setFill()
            }
            
            let selectionPath = NSBezierPath.init(roundedRect: selectionRect, xRadius: 0, yRadius: 0)
            selectionPath.fill()
        }
    }
    
}

Change menu_table_selection_color value in Assets.xcassets file.

Custom NSTableRowView

Now go to your NSTableViewDelegate’s method add your custom NSTableRowView.

 func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
        return MenuTableRowView()
}

Here you can see how my Storyboard looks like. Table view highlight value must be regular.

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •