Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 712
vy32 Avatar asked Sep 12 '15 00:09

vy32


2 Answers

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.)

like image 198
Michael Avatar answered Sep 26 '22 23:09

Michael


I was able to do this by using a Cell-based NSTableView. Make the TableView look like this: Table View in Interface builder

Set the tableColumn to look like this:

tableCOlumn

Set the buttonView to look like this:

enter image description here

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.

like image 30
vy32 Avatar answered Sep 24 '22 23:09

vy32