xcodemacosswiftnstableview

How ro change NSTableHeaderView's background color without hiding column's titles?


I have view-based NSTableView on my Swift OS X app using storyboards, which have 12 columns.

I subclassed my headerview and tried to different things to change background color, but all of them hide my titles also.

This is one of many examples what tried to do:

override func drawRect(dirtyRect: NSRect) {
    super.drawRect(dirtyRect)

    // Drawing code here.
    var myLayer = CALayer()
    myLayer.frame = self.frame
    myLayer.backgroundColor = NSColor.greenColor().CGColor
    self.layer?.addSublayer(myLayer)

That example on fill whole headerview with greencolor so I tried to tell that I want title's to my columns like that:

self.tableView?.tableColumnWithIdentifier("date")?.title = "Date"

...But nothing happens. Can anyone please help?


Solution

  • In one of my apps I wanted to do (nearly) the same plus a bit more (changing the height of the headerView). Therefore I subclassed (not the NSTableHeaderView but) NSTableHeaderCell with my own subclass copying title, font, stringValue etc. from the original cell. (I was not able to do this in IB.)

    I first replaced programmatically all cells of the headerView with objects of my class. And here (in the method - (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView) I set the backGroundColor. That works well.

    My hint: Do not set the backGroundColor in (a subclass of NSTableHeaderView) but in a subclass of NSTableHeaderCell.