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)
}
}
我试图用
更改标题颜色tableColumn.headerCell.textColor = .secondaryLabelColor
但这没有用。我最终使用了以下内容:
tableColumn.headerCell.attributedStringValue = NSAttributedString(string: tableColumn.title, attributes: [.foregroundColor: NSColor.secondaryLabelColor])
已经有一段时间没有人解决这个问题了。我在使用 Swift 5 和 Xcode 12 时遇到了同样非常令人沮丧的问题。这是我使用不需要子类化的 nstableview 方法学到的知识。
在 func tableView(_ myTable: NSTableView... 的开头添加以下代码行:
tableColumn?.headerCell.drawsBackground = true
tableColumn?.headerCell.backgroundColor = fill1Tint
此代码更改 headerCell 背景颜色(fill1Tint 是一些 NSColor)。
然后添加:
let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center
在每个 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])
此代码支持不同的背景和居中的属性文本。