出于某种原因,我的 TableView 的 NSButtonCell 将错误的对象作为参数传递。单击后,我试图读取 NSButtonCell 的标签。
这是我的代码的简化版本:
- (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 TAG: 0
-[NSTableView title]: unrecognized selector sent to instance 0x100132480
乍一看(至少对我而言)这应该表明标签是 100,但事实并非如此。 此外(从第二个控制台输出中可以看出),发送到“buttonClick”选择器的参数似乎不正确,我相信它应该接收 NSButtonCell,但它接收的是 NSTableView。
最佳答案
显然发件人是您的表格 View ,但不是您的特定表格 View 单元格。
我不知道如何让表格单元格成为发送者,但你可以通过查找被点击的行和列的索引知道点击了哪个单元格,然后你可以在单元格之后做应该发生的事情被点击。
- (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]);
}
关于objective-c - NSButtonCell 操作的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2506175/