bhartsb
bhartsb

Reputation: 1356

How to create a 1 column tableview of checkboxes in cocoa

What are the correct steps to create a single column tableview with a fixed number of checkboxes. For example the column could have the following (X indicates the checkbox checked, _ indicates the checkbox unchecked. I also desire text headings in the same column.):

Heading one:

X item 1

_ item 2

X item 3

X item 4

Heading two:

X item 5

_ item 6

I prefer to do this using Cocoa bindings if possible. Also I need to know how to get the on/off checked states of any items that the user checks or unchecks. I need to know how to set the title text of the checkboxes to "item 1", "item 2" etc.

What I'm trying to do is use tableview to create a listbox of items with checkboxes like can be done in Microsoft MFC. Please be explicit in code explanations and describing IB steps as I'm very new to Cocoa and Objective-C.

Thanks.

Upvotes: 0

Views: 732

Answers (2)

goooseman
goooseman

Reputation: 619

OK, I have made this project for you and recorded in a screencast how I have made it.
Everything is so laggy just because it is too hard to screencast for my old 2008y MacBook

Project: Download
Screencast: Download

Upvotes: 1

goooseman
goooseman

Reputation: 619

I'm writing from an iPad, so sorry for any mistakes, I can't test the code
1) in IB put a nstableview, make it 1 column in inspector, make it view based, name the column MainCoumn. Put checkbox in the tableviewcell.
2) select yor table view, open the forth tab in the inspector and connect delegate and datasource with AppDelegate.
3) in your AppDelegate.h add this:

<NSTableViewDelegate, NSTableViewDataSource>  

After : NSObject

4) in your AppDelegate.m add this:

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {

NSTableCellView *cellView = [tableView makeViewWithIdentifier:tableColumn.identifier owner:self];
if( [tableColumn.identifier isEqualToString:@"MainColumn"] )
{
    NSArray *subviews = cellView.subviews;
    NSButton *checkbox = [subviews objectAtIndex:1];
    cellView.textField.stringValue = @"checkbox";
   //  [checkbox state];  - check is it checked
  //   [checkbox setState:0];  - 0 is to set it unchecked, 1- checked. 
    // if you need to make the second one checked, other - unchecked:
   if (row == 1) {
    [checkbox setState:1];
    } else {
     [checkbox setState:0]; 
    }
    return cellView;
}
return cellView;    
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
return 6 
   // here you type the number of rows
}

5) profit111

Upvotes: 0

Related Questions