How do I override layout of NSTableHeaderView?

前端 未结 4 1808
说谎
说谎 2021-01-06 06:30

I am trying to produce a custom header for my NSTableView. I would like to change the font of the header text and remove the borders and vertical separators.

My curr

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-06 07:07

    You will need to take over the drawing yourself by subclassing NSTableHeaderCell, like so:

    final class CustomTableHeaderCell : NSTableHeaderCell {
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override init(textCell: String) {
            super.init(textCell: textCell)
            self.font = NSFont.boldSystemFontOfSize(20)
        }
    
        override func drawWithFrame(cellFrame: NSRect, inView controlView: NSView) {
            // skip super.drawWithFrame(), since that is what draws borders
            self.drawInteriorWithFrame(cellFrame, inView: controlView)
        }
    
        override func drawInteriorWithFrame(cellFrame: NSRect, inView controlView: NSView) {
            let titleRect = self.titleRectForBounds(cellFrame)
            self.attributedStringValue.drawInRect(titleRect)
        }
    }
    

    If you are setting up the table programmatically, you would do it like:

    let col = NSTableColumn(identifier: id)
    col.headerCell = CustomTableHeaderCell(textCell: title)
    col.title = title
    self.dataTableView.addTableColumn(col)
    

    Otherwise, you should be able to just set the name of your class to your subclass' name in Interface Builder.

提交回复
热议问题