Search code examples
swiftcocoafontssizenstableview

How to change font size of NSTableHeaderCell


I am trying to change the font size of my NSTableView within my code to allow the user to change it to their liking. I was successful by changing the font size of each NSTableCellView but failed to do so by the header cells.

I was trying to do it like this

let headerCell = NSTableHeaderCell()
let font = NSFont(name: "Arial", size: 22.0)
headerCell.stringValue = "firstname"
headerCell.font = font
customerTable.tableColumns[0].headerCell = headerCell

The stringValue of the header cell will be set accordingly but the size does not change. How can I change the font size of my headers?

Thanks

Oliver


Solution

  • You can create a NSTableHeaderCell subclass and implement the property you want to change.

    In Objective-C (I'm not good at Swift):

    @implementation CustomTableHeaderCell
    
    -(NSFont *)font {
        return [NSFont fontWithName:@"Arial" size:22];
    }
    
    // you can alse custom textColor
    -(NSColor *)textColor {
        return [NSColor redColor];
    }
    
    @end
    

    Assign CustomTableHeaderCell:

    CustomTableHeaderCell *headerCell = [[CustomTableHeaderCell alloc] init];
    headerCell.stringValue = @"Header title";
    self.tableView.tableColumns[0].headerCell = headerCell;
    

    Screenshot

    In Cocoa, there are many things you can't change its style by cell.font = ..., you need to create a subcalss.