Swift: Unable to add NSTableHeaderCell to NSTableView

593 views Asked by At

So I'm drawing an NSTableView programmatically, however, I'm unable to draw the header. Any ideas?

let tableContainer: NSScrollView = NSScrollView(frame: NSMakeRect(20, 50, 380, 200))
let tableView: NSTableView = NSTableView(frame: NSMakeRect(0, 0, 364, 200))
let tableViewHeader: NSTableHeaderView = NSTableHeaderView(frame: NSMakeRect(0, 0, 364, 20))

let header1: NSTableHeaderCell = NSTableHeaderCell(textCell: "H1")
let header2: NSTableHeaderCell = NSTableHeaderCell(textCell: "H2")

let col1: NSTableColumn = NSTableColumn(identifier: "col1")
let col2: NSTableColumn = NSTableColumn(identifier: "col2")
col1.width = 200
col2.width = 200
col1.headerCell = header1

tableView.headerView = tableViewHeader
tableView.addTableColumn(col1)
tableView.addTableColumn(col2)

tableView.setDelegate(self)
tableView.setDataSource(self)
tableView.reloadData()

tableContainer.addSubview(tableView)
tableContainer.hasVerticalScroller = true

self.view.addSubview(tableContainer)
1

There are 1 answers

0
Astin On

You can use NSClipView which includes table header and contents , then add NSClipView to NSScrollview as creating tableview on xib.

or it doesn't need to add NSClipView. The point is addSubview with not only tableview but tableheaderview.

let tableScrollView = NSScrollView(frame: NSMakeRect(0, 0, 300, 430))
let tableHeaderView: NSTableHeaderView = NSTableHeaderView(frame: NSMakeRect(0, 0, 300, 17))
let tableView = NSTableView(frame: NSMakeRect(0, 0, 300, 430))

self.col1.headerCell = header1
self.col2.headerCell = header2
self.col1.width = 130
self.col2.width = 200

self.tableView.headerView = tableHeaderView
self.tableView.allowsMultipleSelection = true
self.tableView.usesAlternatingRowBackgroundColors = true

self.tableView.addTableColumn(col1)
self.tableView.addTableColumn(col2)

self.tableView.focusRingType = NSFocusRingType.None
self.tableView.autoresizesSubviews = true
self.tableView.setDelegate(self)
self.tableView.setDataSource(self)
self.tableView.reloadData()

self.tableScrollView.addSubview(tableView)
self.tableScrollView.addSubview(tableHeaderView)

self.tableScrollView.documentView = tableView
self.tableScrollView.hasVerticalScroller = true
self.tableScrollView.borderType = NSBorderType.BezelBorder


self.view.addSubview(tableScrollView)