简体   繁体   中英

macOS - How do I use checkbox in NSTableView?

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

NSTableCellView has a imageView and a textField outlet. You need a checkbox and you can add one. Subclass NSTableCellView and add an outlet 'checkBox'. In IB, change the class of the cell view, replace the textfield by a checkbox (or add a checkbox) and connect the 'checkBox' outlet. In tableView(_:viewFor:row:) , use checkBox instead of textField .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM