Search code examples
objective-ccocoa

Programmatically fill one tableview, use IB bindings to fill others


A window is created in a xib, and it contains two tableviews, A and B. In interface builder, both A and B have the File's owner set as the delegate, since both will use some delegate methods, e.g. for drag and drop.

I would like to fill table A programmatically, i.e. using -tableView:viewForTableColumn:row:, but I would still like to fill table B using the Bindings tab in interface builder.

Is this possible directly?

It seems that in my case, having the delegate of both tableviews set to the file's owner will automatically mean that B is populated using delegate methods, overriding anything set in the IB.


Solution

  • It seems that in my case, having the delegate of both tableviews set to the file's owner will automatically mean that B is populated using delegate methods, overriding anything set in the IB.

    No, tableView:viewForTableColumn:row: and bindings work well together. Just do what the documentation says:

    It’s recommended that the implementation of this method first call the NSTableView method makeViewWithIdentifier:owner: passing, respectively, the tableColumn parameter’s identifier and self as the owner to attempt to reuse a view that is no longer visible or automatically unarchive an associated prototype view for that identifier.

    When using Cocoa bindings, this method is optional if at least one identifier has been associated with the table view at design time. (Note that a view’s identifier must be the same as the identifier of its column. An easy way to achieve this is to use the Automatic identifier setting in Interface Builder.)

    Example:

    - (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
        if (tableView == self.tableViewA) {
            MyTableCellView *cellView = [tableView makeViewWithIdentifier:myIdentifier owner:self];
            cellView.customView.data = myData;
            return cellView;
        }
        else {
            return [tableView makeViewWithIdentifier:tableColumn.identifier owner:self];
        }
    }