【问题标题】:Customise NSTableView Header, background color, remove border自定义 NSTableView Header、背景颜色、移除边框
【发布时间】:2019-06-14 22:54:39
【问题描述】:

我需要添加背景颜色,更改标题字体并删除我的 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
}

}

【问题讨论】:

  • 该代码不起作用
  • 接受的答案有效,但不会删除边框。另一个答案需要调整。可以选择浮动组行吗?
  • 是的,我不知道什么是浮动组行

标签: swift macos cocoa nstableview


【解决方案1】:

首先,您将自定义 NSTableHeaderCell 分配给 NSTableView 的每个单元格。 这可以在 NSTableView 的子类(如下)或视图控制器(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)
    }

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

【讨论】:

  • 不错的代码,但是如果我们点击标题,视图就会变成一个奇怪的东西
  • 你的意思是文字往下移?默认情况下,表头是可点击的,并且允许在适当的实现中更改排序顺序。我只专注于如何自定义绘图。根据您的要求,您将不得不停用此行为或同时实施它。
  • 如何在绘图函数中移除边框?
  • 应该有不同的绘图功能可以玩。我停止使用它并继续使用 SwiftUI。你也应该这样做:-)
猜你喜欢
  • 2011-08-23
  • 2023-03-22
  • 2017-04-30
  • 2015-03-07
  • 1970-01-01
  • 2011-09-12
  • 2015-02-25
  • 2015-07-05
  • 1970-01-01
相关资源
最近更新 更多