Automatic table column Indentifier in NSTableView

十年热恋 提交于 2019-12-04 17:53:38

First of all you should not get the index of the column, as the columns can be dragged and hence its index can be changed. However you can do as:

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{

    if ([tableView tableColumns][0] == tableColumn) {
        return [self.array[row] firstName];
    }
    else if ([tableView tableColumns][1] == tableColumn) {
        return [self.array[row] lastName];
    }
}

The other way around is to check with the table header cell title. Using this you can decide what value to fill in the column. Something like: (But here you need to set the column header manually)

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{

    NSCell *headerCell = [tableColumn headerCell];

    if ([[headerCell title] isEqualToString:@"First Name"]) {
        return [self.array[row] firstName];
    }
    else if ([[headerCell title] isEqualToString:@"Last Name"]) {
        return [self.array[row] lastName];
    }

    return nil;
}

Also you can opt for Cocoa-Binding, here no need to use identifiers!!!


Edit:

As you don't have class, infact you are dealing with basic C-array. But the delegate returns id so you need to typecast it to some Obj-C object. In following case I use NSString. See the screen shot :

But the column identifier is not an Integer... and therefore your "intValue" will always bring a 0 out of it.

The column Identifier (whether automatic, or provided by the user when defining the table, either programmatically or using the UI editor) is an NSString. It is used not only for finding an NSColumn, but also for automatically persisting column attributes in NSUserDefaults.

Another wrong assumption - is that the column identifier has to do with its index. It is NOT. Columns can be re-arranged (by dragging them around, or programmatically) so their index can change.

So - to adapt your code sample to working with column identifiers - I would recommend that you will not work with a 2-dimensional array (with indexes for both rows and columns) but rather use an NSDictionary for the per-column information, where the key (NSString) will be the column identifier, and the value - the value of the cell you need.

So: indexes for rows, keys for column identifiers, your sample lines would look like this:

//in the objectValueForTableColumn blah blah blah method

NSString columnIdentifier = [aTableColumn identifier];
return [[myArray objectAtIndex: rowIndex] valueForKey: columnIdentifier];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!