Question

I've got a view-based NSTableView, using Cocoa Bindings to change the values of some labels and images in the cell. It all works great. However, I want to add a button to the cell. I've got the button working, but its action method only has the button as sender, which means I have no idea of the content of the cell that the button is in. Somehow I need to store some extra data on the button - at the very least the row index that the button is in. I subclassed NSButton and used my subclass in the cell, but Interface Builder doesn't know about the extra property so I can't bind to it. If I wanted to bind it in code, I don't know the name of the object or keypath that would be passed to it.

How can I get this to work?

Was it helpful?

Solution

You can use rowForView in your action method to get the row value

- (IBAction)doSomething:(id)sender
{
        NSInteger row = [_myTableView rowForView:sender];
}

OTHER TIPS

You can use the Identity field in Interface Builder to associate a table cell view from the nib with an instance in your code:

enter image description here

Additionally you have to implement - tableView:viewForTableColumn:row: in your table view's delegate. (Don't forget to connect the delegate in IB)

 - (NSView*)tableView:(NSTableView*)tableView viewForTableColumn:  
(NSTableColumn*)tableColumn row:(NSInteger)row
    {
        SSWButtonTableCellView *result = [tableView makeViewWithIdentifier:@"ButtonView" owner:self];
        result.button.title = [self.names objectAtIndex:row][@"name"];
        result.representedObject = [self.names objectAtIndex:row];
        return result;
    }

I added representedObject property in my NSTableCellView subclass, which I set in the above table view delegate method.

Your custom table cell view can later use that object in it's action. e.g.:

- (IBAction)doSomething:(id)sender
{
    NSLog(@"Represented Object:%@", self.representedObject);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top