Search code examples
xcodecheckboxrowsnstableviewnstablecolumn

Implement checkbox in NSTableView in mac application


First of all, I searched for 3 days and have not found what I am looking for.

Second point, I am VERY new to Xcode programming so PLEASE keep your answer as simple and/or detailed as possible!

Inside my NSTableView I need the first column to be text followed by X number of checkbox columns with the last column to be text. The X number of columns is a variable based on the number of entries I read from a SQLite file.

My questions are:

  • How do I define at runtime what type and how many columns I have?
  • How do I know whether a checkbox value is checked or not?
  • How do I add rows to the tableview if I don't know the number of cells it has?

Thanks for taking the time to answer!

Best regards, Igor


Solution

  • You want to create a table at runtime, and you dont know how many columns will be there!!!

    Thats a big deal.

    Read NSTableView documentation and you will find addTableColumn: method. in the loop go on to create colmn and dont forget to give identifier to all columns.

    And over this you want to have a checkbox. Creating checkbox is not difficult either.

    EDIT:

    For checkbox implementation, find a project here.

    Draw a checkBoxCell in the column you want to have checkbox. Or you can do it programatically.

    I did it through IB.

    You should create an array that will store the states for each(number of rows) checkboxes.

    - (id)init {
        self = [super init];
        if (self) {
    
            states=[[NSMutableArray alloc] initWithObjects:@"1", @"0", @"1", nil];
        }
        return self; }
    
    
    
    - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
        NSLog(@"Num of rows---- %ld", [names count]);
        return [names count];
    }
    

    Check for tableIdentifier having value "check".

    - (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
        if ([[tableColumn identifier] isEqualTo:@"name"]) {
            return [names objectAtIndex:row];
        }
        else if ([[tableColumn identifier] isEqualTo:@"check"]) {
    
            return [states objectAtIndex:row];
        }
        else if ([[tableColumn identifier] isEqualTo:@"states"]) {
            return [states objectAtIndex:row];
        }
        return 0;
    }
    

    Update the value of checkbox as per on/off.

    - (void)tableView:(NSTableView *)tableView setObjectValue:(id)value forTableColumn:(NSTableColumn *)column row:(NSInteger)row {          
        [states replaceObjectAtIndex:row withObject:value];
        [tableView reloadData]; 
    }