1

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

4

2 に答える 2

5

@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)
    }
}
于 2016-09-17T21:32:53.040 に答える