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 正在绘制”,但表格标题的字体没有改变。

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 回答
0

自从有人回答这个问题以来已经有一段时间了。我在使用 Swift 5 和 Xcode 12 时遇到了同样非常令人沮丧的问题。这是我使用不需要子类化的 nstableview 方法所学到的。

  1. 在 func tableView(_ myTable: NSTableView... 的开头添加以下代码行:

     tableColumn?.headerCell.drawsBackground = true
     tableColumn?.headerCell.backgroundColor = fill1Tint 
    

此代码更改 headerCell 背景颜色(并且 fill1Tint 是一些 NSColor)。

然后加:

    let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = NSTextAlignment.center
  1. 在每个 tableColumn.identifier 块中,添加一个属性文本字符串,例如:

         let title: String = "Value"
         tableColumn?.headerCell.attributedStringValue = NSAttributedString(string: title, attributes: [
             NSAttributedString.Key.font: fontMedium,
             NSAttributedString.Key.foregroundColor: text1Tint,
             NSAttributedString.Key.paragraphStyle : paragraphStyle])
    

此代码启用不同的背景和居中的属性文本。

于 2021-02-04T21:00:15.213 回答