sam*_*sam 1 macos cocoa nstableview nstableheadercell swift3
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 正在绘制”,但表格标题的字体没有改变。
感谢@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)
    }
}
| 归档时间: | 
 | 
| 查看次数: | 2550 次 | 
| 最近记录: |