2016-09-16 60 views
0

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://stackoverflow.com/questions/32666795/how-do-i-override-layout-of-nstableheaderview) –

回答

2

感謝來自@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) 
    } 
} 
相關問題