sharkyenergy sharkyenergy - 8 months ago 60
Objective-C Question

Populate NSTableView with unknown number of columns

I have a NSTableview and a button. NSTableview has a unknown number of columns.

The first column has a image well and 2 text boxes, the others (again, unknown number) are normal textbox columns.

The button opens up a file open dialogue. Once I choose the files (.jpg) I would like to process them.

So far everything is made (chose files, columns, etc..) what is missing is the populating of the table:

I have the loop that goes through all the selected files. What is the best way to do this:

  • display the image in the image well of the first cell,

  • type the filename in the first textbox of the first cell,

  • type the filepath in the second cell of the textbox,

  • type "YES" in all other columns.

My difficulty is that I have no idea how many columns will be there since it depends from the user. The number of columns will not change during Runtime. they are set up at startup based on the configuration. if the configuration is changed then the app should be reloaded.

I am a beginner in Objective-C/Cocoa programming.

additional info as requested:

It is a view based NSTableView
each column represents an action that has to be taken in a later moment on an image. the program user can decide what and how many actions to take, thats the reason for a unknown amount of columns in the table view.

Answer Source

You can add columns programmatically using addTableColumn:. This method takes an NSTableColumn instance that you can create in your code.

The rest of your architecture (displaying images, etc.) does not particularly change from "normal" code just because the columns have been added dynamically.

Here is a snippet that should get you started:

NSTableColumn* tc          = [[NSTableColumn alloc] init];

NSString *columnIdentifier = @"NewCol"; // Make a distinct one for each column
NSString *columnHeader     = @"New Column"; // Or whatever you want to show the user

[[tc headerCell ] setStringValue: columnHeader];
tc.identifier = columnIdentifier;

// You may need this one, too, to get it to show.
self.dataTableview.headerView.needsDisplay = YES;

When populating the table, and assuming that the model is an array (in self.model) of NSDictionary objects, it could go something like this;

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

     NSString *columnIdentifier = tableColumn.identifier;

     NSDictionary *rowDict = [self.model objectAtIndex: row];

     NSString *value = [rowDict valueForKey: columnIdentifier]; // Presuming the value is stored as a string 

     // Show the value in the view

More in the docs.