I have successfully created a cell-based NSTableView purely in code. I would like to make the cells a little more interesting and I have read that I need to create a view-ba
This was quite useful in my attempt to program scrolling tables without IB & Nibs. Here's my toy version, updated to Swift 4.2.
The custom cell view subclass is only there to let me see that cells actually get re-used, which they do:
import Cocoa
class DIYTableViewDataSource: NSObject, NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return 25
}
}
class CustomTableCellView: NSTableCellView {
var count = 1
}
func createCell(_ id: NSUserInterfaceItemIdentifier) -> CustomTableCellView {
// Create a text field for the cell
let textField = NSTextField()
textField.backgroundColor = NSColor.clear
textField.translatesAutoresizingMaskIntoConstraints = false
textField.isBordered = false
// Create a cell
let cell = CustomTableCellView() // Doing this to see that cells get re-used
cell.identifier = id
cell.addSubview(textField)
cell.textField = textField
// Constrain the text field within the cell
textField.widthAnchor.constraint(equalTo: cell.widthAnchor).isActive = true
textField.heightAnchor.constraint(equalTo: cell.heightAnchor).isActive = true
textField.bind(NSBindingName.value, to: cell, withKeyPath: "objectValue", options: nil)
return cell
}
class DIYTableViewDelegate: NSObject, NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let id = tableColumn!.identifier
var view = tableView.makeView(withIdentifier: id, owner: nil) as? CustomTableCellView
if view == nil {
view = createCell(id)
}
view!.textField!.stringValue = "\(id.rawValue) \(row) \(view!.count)"
view!.count += 1
return view
}
}