2

I spend the last day searching the internet for a way how to set the backgroundcolor of a NSTableHeaderCell. All I achieved was this:

func tableView(_ numberTableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {

        if tableColumn!.identifier == "description" {

            let cell = NSTableHeaderCell()
            cell.title = "Header Title"
            cell.backgroundColor = NSColor.red
            cell.drawsBackground = true
            cell.isBordered = false
            cell.font = NSFont(name: "System", size: 13)
            tableColumn!.headerCell = cell
        }
        return nil
    }

The result Looks like this:

enter image description here

I tried to change the font to NSFont(name: "Helvetica", size: 26), then after launch of the application it looks like:

enter image description here

But after the cell is clicked for the first time, the cell pops smaller again:

enter image description here

I´m wondering if there is a way to set the backgroundcolor of the whole cell, without becoming smaller after click. I also tried to subclass NSTableHeaderView, but this just draws the whole HeaderView and no more titles could be set. It would be a big help to get some ideas.

EDIT:

According to the suggested answer, I tried to subclass NSTableHeaderCell and set: tableColumn?.headerCell = MyHeaderCell()

class MyHeaderCell: NSTableHeaderCell {

    override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
        super.draw(withFrame: cellFrame, in: controlView)
        NSColor.red.set()
        self.backgroundColor = NSColor.red
        NSRectFillUsingOperation(cellFrame, .sourceOver)

    }
}

And this is the result:

enter image description here

So now the whole HeaderView is colored. By clicking one cell, the cell gets white again. Somehow I still didn´t get it how to change the real background of the cell.

Josch Hazard
  • 323
  • 3
  • 20
  • Why do you replace the header cell in `viewForTableColumn`? – Willeke Jul 26 '17 at 15:20
  • Possible duplicate of [How to apply custom styling to NSTableHeaderView?](https://stackoverflow.com/questions/39898446/how-to-apply-custom-styling-to-nstableheaderview) – Willeke Jul 26 '17 at 15:28
  • @Willeke I tried to to perform the suggested solution in your earlier answered question. But I just can´t find out how to do it right. I updated the code with a try of subclassing the Headercell. – Josch Hazard Jul 26 '17 at 18:31

0 Answers0