Question

For some reason the NSButtonCell for my table view is passing the wrong object as a parameter. I am trying to read the tag of the NSButtonCell after it is clicked.

Here is a simplified version of my code:

- (int)numberOfRowsInTableView:(NSTableView *)aTableView {
    return 3;
}

- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex {
    [aCell setTitle:@"Hello"];
    [aCell setTag:100];
}

- (void)buttonClick:(id)sender {
    NSLog(@"THE TAG %d",[sender tag]);
    NSLog(@"THE TITLE: %@",[sender title]);
}

- (void)refreshColumns {
    for (int c = 0; c < 2; c++) {
        NSTableColumn *column = [[theTable tableColumns] objectAtIndex:(c)];

        NSButtonCell* cell = [[NSButtonCell alloc] init];
        [cell setBezelStyle:NSSmallSquareBezelStyle];
        [cell setLineBreakMode:NSLineBreakByTruncatingTail];
        [cell setTarget:self];
        [cell setAction:@selector(buttonClick:)];
        [column setDataCell:cell];
    }
}

- (void)awakeFromNib {
    [self refreshColumns];
}

The resut from the console says:

    THE TAG:   0
    -[NSTableView title]: unrecognized selector sent to instance 0x100132480

At first sight (for me at least) this should say that the tag is 100, but it doesn't. Also (as it can be seen from the second console output), it appears that the parameter being sent to the "buttonClick" selector is incorrect, I believe it should be receiving the NSButtonCell, but it is receiving the NSTableView.

Was it helpful?

Solution

Apparently the sender is your table view but not your specific table view cell.

I have no idea about how to let the table cell become the sender, but you can know which cell is clicked by looking for the index of the clicked row and column, and then you can do what ought to happen after the cell is clicked.

- (void)buttonClick:(id)sender {
    NSEvent *event = [NSApp currentEvent];
    NSPoint pointInTable = [tableView convertPoint:[event locationInWindow] fromView:nil];
    NSUInteger row = [tableView rowAtPoint:pointInTable];
    NSTableColumn *column = [[tableView tableColumns] objectAtIndex:[tableView columnAtPoint:pointInTable]];
    NSLog(@"row:%d column:%@", row, [column description]);
}

OTHER TIPS

In this case the sender is indeed an NSTableView but you can retrieve the row and column of the control that actually triggered the event simply with [sender clickedRow] and [sender clickedColumn].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top