swift - 自定义 NSTableView 表头、背景色、去除边框

标签 swift macos cocoa nstableview

我需要添加背景颜色、更改标题字体并移除 NSTableView 标题上的边框。

我已经绘制了红色背景并调整了页眉高度大小,但我找不到任何方法来进一步自定义它。这是我所能达到的:

override func viewDidLoad() {
    super.viewDidLoad()
    myTable.tableColumns[0].headerCell = CustomHeaderCell()
    myTable.headerView?.frame.size.height = 50
}


class CustomHeaderCell: NSTableHeaderCell {
    override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
    super.draw(withFrame: cellFrame, in: controlView)
    controlView.layer?.backgroundColor = NSColor.red.cgColor
}

enter image description here

最佳答案

首先,您要将自定义的 NSTableHeaderCell 分配给 NSTableView 的每个单元格。 这可以在 NSTableView 的子类(如下所示)或 View Controller (viewDidLoad) 中完成

override func awakeFromNib() {

    for column in self.tableColumns{
        column.headerCell = HeaderCell(textCell: column.headerCell.stringValue)
    }
}

在您的自定义 NSTableHeaderCell 中,您可以覆盖 func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) 以自定义绘图和文本。

    override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {

    NSColor.green.set()

    let rect = NSRect(x: cellFrame.origin.x, y: cellFrame.origin.y - 3, width: cellFrame.size.width - 2, height: cellFrame.size.height + 10)
    NSBezierPath(rect: rect).fill()

    let str = NSAttributedString(string: stringValue, attributes:
        [NSAttributedString.Key.foregroundColor: NSColor.red,
         NSAttributedString.Key.font: NSFont(name: "Skia", size: 14)])

    str.draw(in: cellFrame)

}

要进一步自定义单元格绘图(如边框)​​,您也可以覆盖 func draw(withFrame cellFrame: NSRect, in controlView: NSView)

   override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
        self.drawInterior(withFrame: cellFrame, in: controlView)
    }

当然,您可以使用硬编码属性或单元格提供的属性。

关于swift - 自定义 NSTableView 表头、背景色、去除边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54291857/

相关文章:

ios - 无法更改 iOS 13 中大标题的导航栏色调颜色

swift - 每天更改重复提醒的内容

objective-c - 在哪里寻找错误。文档、应用程序委托(delegate)或两者兼而有之?

macos - GitHub Mac 应用程序不断添加 SSH key ?

java - C++ JNI想要安装Mac Legacy JRE6

cocoa - 将 NSTextfield 添加到 NSRect

iOS 推送通知和 AppDelegate 方法行为

ios - 具有 2 个数据集的多折线图

cocoa - 如何从 AppDelegate 获取特定 Controller

macos - 为什么我在尝试添加标题栏附件 View 时遇到 "titlebarViewController not supported for this window style"异常