Setting the highlight colour of a selected cell in NSTableView

That's a question for Mac app (Cocoa).

I want to change the standard highlighting.

I thought to use tableView.selectionHighlightStyle.

But there are only 2 values: .none and .regular. Cannot find how to define a custom one.

So I tried a workaround:

  • set tableView.selectionHighlightStyle to .none
    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        
        tableView.selectionHighlightStyle = .none 
  • keep track of previousSelection
  • Then, in tableViewSelectionDidChange
    • reset for previousSelection
    func tableViewSelectionDidChange(_ notification: Notification) { }

        if previousSelection >= 0 { 
            let cellView = theTableView.rowView(atRow: previousSelection, makeIfNecessary: false)
            cellView?.layer?.backgroundColor = .clear
        }
    • set for the selection to a custom color
            let cellView = theTableView.rowView(atRow: row, makeIfNecessary: false)
                cellView?.layer?.backgroundColor = CGColor(red: 0, green: 0, blue: 1, alpha: 0.4)
            previousSelection = row

Result is disappointing :

Even though tableView.selectionHighlightStyle is set to .none, it does overlays the cellView?.layer

Is there a way to directly change the color for selection ?

You definitely wouldn't want to change the highlight style in "viewFor". Maybe do that in viewDidLoad or something.

Your terminology isn't quite right. You're getting a row view and setting the layer colour on it. There's nothing wrong with that, and it would be a correct solution. But it's not "cellView".

It looks like your actual cellView is drawing its own background. That's what you would want to disable. (Unless you wanted to do the selection drawing at the cell view level).

There's more than one way to do this. TableViews are just really complicated if you try to do anything fancy with them.

Thanks for reply.

 

You definitely wouldn't want to change the highlight style in "viewFor". Maybe do that in viewDidLoad or something.

What's the issue ?

 

There's more than one way to do this.

One would be enough

Anyway, I change my mind to stay consistent with system behaviour and will change the color of the text (to white) when selected, to make it more readable.

Setting the highlight colour of a selected cell in NSTableView
 
 
Q