我最后一天在互联网上搜索如何设置 NSTableHeaderCell 背景颜色的方法。我所取得的成就就是:
func tableView(_ numberTableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if tableColumn!.identifier == "description" {
let cell = NSTableHeaderCell()
cell.title = "Header Title"
cell.backgroundColor = NSColor.red
cell.drawsBackground = true
cell.isBordered = false
cell.font = NSFont(name: "System", size: 13)
tableColumn!.headerCell = cell
}
return nil
}
结果看起来像这样:
我尝试将字体更改为
NSFont(name: "Helvetica", size: 26)
,然后启动应用程序后,它看起来像:
但是第一次单击单元格后,单元格再次变小:
我想知道是否有一种方法可以设置整个单元格的背景颜色,而不会在单击后变小。我还尝试对 NSTableHeaderView 进行子类化,但这只会绘制整个 HeaderView 并且无法设置更多标题。获得一些想法将会有很大帮助。
编辑:
根据建议的答案,我尝试对 NSTableHeaderCell 进行子类化并设置:
tableColumn?.headerCell = MyHeaderCell()
class MyHeaderCell: NSTableHeaderCell {
override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
super.draw(withFrame: cellFrame, in: controlView)
NSColor.red.set()
self.backgroundColor = NSColor.red
NSRectFillUsingOperation(cellFrame, .sourceOver)
}
}
这就是结果:
现在整个 HeaderView 都是彩色的了。单击一个单元格,该单元格会再次变白。不知怎的,我仍然不明白如何改变单元格的真实背景。
class ViewController: NSViewController {
@IBOutlet weak var listTableView: NSTableView!
override func viewDidLoad() {
super.viewDidLoad()
// Set custom header cell class for each table column
for aColumn in listTableView.tableColumns {
let customHeaderCell = CustomHeaderCell(textCell: aColumn.headerCell.stringValue)
customHeaderCell.font = NSFont.systemFont(ofSize: 13, weight: .regular)
customHeaderCell.textColor = NSColor.white
aColumn.headerCell = customHeaderCell
}
}
}
[![enter image description here][1]][1]class CustomHeaderCell: NSTableHeaderCell {
override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
// Draw background color
NSColor.red.setFill()
NSBezierPath(rect: cellFrame).fill()
// Draw separator line
NSColor.lightGray.set()
NSBezierPath(rect: NSRect(x: cellFrame.origin.x + cellFrame.size.width, y: cellFrame.origin.y, width: 1.0, height: cellFrame.size.height)).fill()
// Draw header text
let interiorFrame = CGRect(x: cellFrame.origin.x + 4.0, y: cellFrame.origin.y + 6.0, width: cellFrame.size.width, height: 13.0)
drawInterior(withFrame: interiorFrame, in: controlView)
}
}