Issues with NSButtonCell action

For some reason, NSButtonCell is passing the wrong object as a parameter to my table view. I try to read the NSButtonCell tag after clicking it.

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]; } 

To the right of the console it says:

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

At first glance (at least for me) this should say that the tag is 100, but it is not. Also (as can be seen from the second console output), it seems that the parameter sent to the "buttonClick" selector is incorrect, I believe that it should receive NSButtonCell, but it receives NSTableView.

+4
source share
2 answers

Obviously, the sender is your table view, but not your specific table view cell.

I don’t know how to let the table cell become the sender, but you can find out which cell is clicked by looking for the index of the clicked row and column, and then you can do what should happen after the cell.

 - (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]); } 
+4
source

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

+4
source

Source: https://habr.com/ru/post/1304967/


All Articles