/ / macOS 10.12以降でNSTableViewヘッダをカスタマイズするにはどうすればいいですか? - macos、ココア、nstableview、swift3、nstableheadercell

MacOS 10.12以降でNSTableViewヘッダをカスタマイズするには? - macos、ココア、nstableview、swift3、nstableheadercell

MacOS 10.12以降、Xcode 8以降、Swift 3:

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 is drawing"というメッセージが表示されますが、テーブルヘッダーのフォントは変更されません。

回答:

回答№1は2

@HeinrichGiesenからのコメントとありがとう@ウィルケ、私はそれがうまくいった。背景の色をカスタマイズする私の方法はそれほど柔軟ではないことに注意してください。私は本当にデフォルトの描画を着色するだけです。それは私の目的には十分です。

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)
}
}