Igor Vidrevich
Igor Vidrevich

Reputation: 93

changing background color for the headers in NSTableView

Im trying to change the background color of a header row in a view-based NSTableView but not having any luck

tried this:

tableView.headerView?.layer?.backgroundColor = CGColor.black

and this (as was suggested in an earlier Obj-C post from a while ago):

for column in tableView.tableColumns {
    column.headerCell.backgroundColor = NSColor(red: 0/255, green: 108/255, blue: 178/255, alpha: 1)
    column.headerCell.textColor = NSColor.blue
}

Upvotes: 2

Views: 2395

Answers (3)

Stefanf
Stefanf

Reputation: 1693

Adding a colored subview is probably the cleanest way to achieve this. It goes between the default background and the cells that draw the header text and controls

NSRect rect = tableview.headerView.frame;
rect.size.width = 10000; /// just pick something wide enough here
MyColoredView * coverView = [[MyColoredView alloc] initWithFrame:rect];
coverView.autoresizingMask = tableview.headerView.autoresizingMask;
[tableview.headerView.superview addSubview:aView positioned:NSWindowBelow relativeTo:tableview.headerView];

Upvotes: 0

Kien Nguyen
Kien Nguyen

Reputation: 11

I also have same problem. I found out that the headercell is inherit from NSTextFieldCell. Which have background Color properties. you can access to that and set it to new color. remember to set draw background to YES.

*when you create new column*
[[newCol headerCell] setDrawsBackground:YES];


- (void)tableView:(NSTableView *)tableView didClickTableColumn:(NSTableColumn *)tableColumn{
    [[tableColumn headerCell] setBackgroundColor:<color you want to change to>];
}

Upvotes: 0

Kaschman
Kaschman

Reputation: 151

Creating a custom NSTableHeaderCell subclass and setting NSTableColumn's headerCell property allows you to customize the appearance of your table's header row.

Apple's documentation recommends overriding the drawInterior:withFrame method when customizing a header cell, but this will not fill the background color for the whole cell - overriding draw:withFrame is needed. Calling drawInterior will draw the header's label and other elements. If you want to keep the header's content centered vertically in the cell, adjusting the interior frame is necessary.

override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
    NSColor.gray.setFill()
    NSBezierPath.fill(cellFrame)

    let interiorFrame = CGRect(x: cellFrame.origin.x, y: cellFrame.origin.y + 4.0, width: cellFrame.size.width, height: 14.0)
    drawInterior(withFrame: interiorFrame, in: controlView)
}

One thing to note - the column separator lines will need to be drawn as well if you want them.

Upvotes: 1

Related Questions