如何在macOS 10.12+上自定义NSTableView标题?

问题描述:

MacOS 10.12+,Xcode 8+,Swift 3:如何在macOS 10.12+上自定义NSTableView标题?

我想以编程方式自定义NSTableView标头的字体和绘图。我知道有关于这个问题的老问题,但我今天找不到任何有效的问题。

例如,我试图子类NSTableHeaderCell设置自定义字体:

class MyHeaderCell: NSTableHeaderCell { 
    override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) { 
     NSLog("MyHeaderCell is drawing") 
     font = NSFont.boldSystemFont(ofSize: 12) 
     super.drawInterior(withFrame: cellFrame, in: controlView) 
    } 
} 

,然后使用该子类在我的表视图:

tableColumn.headerCell = MyHeaderCell() 

我看到消息“MyHeaderCell正在制定“在控制台中,但表头的字体不会改变。

+1

您是否尝试过设置'attributedStringValue'? – Willeke

+0

@Willeke是的,我试着设置的attributesStringValue。我的设置被忽略。 – sam

+1

@sam在使用'attributedStringValue'实现MyHeaderCell的过程中完美无瑕!所以我想你的代码有问题。你可能会发现一些提示[here](http://*.com/questions/32666795/how-do-i-override-layout-of-nstableheaderview) –

感谢来自@HeinrichGiesen和@Willeke的评论,我得到了它的工作。我会在这里发布它,以便它可以帮助某个人。请注意,我自定义背景颜色的方式并不那么灵活。我真的只是默认绘图。这对我的目的来说足够了。

final class MyHeaderCell: NSTableHeaderCell { 

    // Customize background tint for header cell 
    override func draw(withFrame cellFrame: NSRect, in controlView: NSView) { 
     super.draw(withFrame: cellFrame, in: controlView) 
     NSColor(red: 0.9, green: 0.9, blue: 0.8, alpha: 0.2).set() 
     NSRectFillUsingOperation(cellFrame, .sourceOver) 
    } 

    // Customize text style/positioning for header cell 
    override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) { 
     attributedStringValue = NSAttributedString(string: stringValue, attributes: [ 
      NSFontAttributeName: NSFont.systemFont(ofSize: 11, weight: NSFontWeightSemibold), 
      NSForegroundColorAttributeName: NSColor(white: 0.4, alpha: 1), 
     ]) 
     let offsetFrame = NSOffsetRect(drawingRect(forBounds: cellFrame), 4, 0) 
     super.drawInterior(withFrame: offsetFrame, in: controlView) 
    } 
}