objective-c - NSButtonCell 操作的问题

标签 objective-c tags nstableview nstableviewcell nsbuttoncell

出于某种原因,我的 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/

相关文章:

iphone - 向自定义导航栏添加按钮

ios 9 objective-c 屏幕尺寸问题

javascript 函数中 HTML 表单标记内的 Javascript

android - 我们可以使用 Android 编程更改 NFC Type 2 标签的 UID 吗?

c# - 区分x :Name and Name in Wpf application

cocoa - 如何在 NSOutlineView 中禁用取消选择行

objective-c - 带有 NSCheckBox 单元格的 NSTableView - 如何拦截行选择?

objective-c - NSOutlineView 子类中内容更改时的通知

ios - Objective-C - Firebase 从数据库检索数据并填充到表中

objective-c - 不同颜色的多边形叠加