I'm trying to put checkbox to the first column of a view based tableView. I dragged a check box button to the column, then the structure is like
Table View
First Column
Check
Check
Text Cell
Then in the tableView
method of the view controller I'm doing
if identifier == "Check" {
let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Check"), owner: self) as! NSTableCellView
return cell
}
I get a run time error Could not cast value of type 'NSButton' to 'NSTableCellView'
, what is the correct way to do it?
It's pretty simple.
In a view based NSTableView
you can use any view which inherits from NSView
as table cell view. The default is NSTableCellView
with a text field but it's also possible to use control objects like NSTextField
or NSButton
without any underlying custom view just by dragging them into the table view canvas.
The error occurs because you have to cast the created view to the proper type. If you are using a checkbox cast the view to NSButton
.
Don't think in terms of cell, think in terms of view. I even recommend to name the variable as view
rather than as cell
.
The NSUserInterfaceItemIdentifier
extension is the recommended pattern to define constants
extension NSUserInterfaceItemIdentifier {
static let check = NSUserInterfaceItemIdentifier(rawValue: "Check")
}
let view = tableView.makeView(withIdentifier: .check, owner: self) as! NSButton