简体   繁体   中英

How do you put and control a checkbox in an NSTableView?

I am looking for a way of programmatically putting a checkbox in the first column of an NSTableView. I want to do it in Swift. I need to be able to read the values of all the buttons and set the button when someone clicks the row.

Is there an easy way to do this? I can't find it...

You need the table view to be view-based, not cell-based. The easiest way IMHO is to put the checkbox into the first column of your table view with the interface builder. It should be a sibling of your text field. I assume you want the first column to just contain a checkbox, and nothing else. In this case you should hide the textfield, so that it does not interfere with the checkbox (click the "hidden" checkbox in interface builder for the textfield).

Option 1: create a subclass of NSTableCellView, name it MyTableCellViewWithCheckbox, and give it a @property (nonatomic,strong) NSButton *checkbox; Change the custom class field from NSTableCellView to MyTableCellViewWithCheckbox for the first column and connect the outlet.

Option 2: (I haven't tested it yet, but I think it should work.) Set the tag of the checkbox to 13. To retrieve the checkbox later from the table view cell, you can use the viewWithTag method.

Next, you need to attach an action to your checkbox, so you should create an IBAction onto your view controller (not onto MyTableCellViewWithCheckbox.) In the action-method you can use the tableviews rowForView method to get the row index of the checkbox the user just tapped. The new state can be received directly from the sender of the action (it is an NSButton).

Also, don't forget that awakeFromNib may be called multiple times in your view controller if you have a table view in it - once for each table view cell you instantiate (this took me some time to figure out.)

I was able to do this by using a Cell-based NSTableView. Make the TableView look like this: “接口”构建器中的表视图

Set the tableColumn to look like this:

TableColumn的

Set the buttonView to look like this:

在此输入图像描述

Set the checkbox by having func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? return 1 for a check and 0 for a non-check.

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