2010-03-24 28 views
4

由於某種原因,我的表視圖的NSButtonCell傳遞了錯誤的對象作爲參數。我試圖在單擊它後讀取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]; 
} 

從控制檯resut說:

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

乍一看(至少對我來說)這應該說是標籤100,但它不。 另外(從第二個控制檯輸出可以看出),看起來發送到「buttonClick」選擇器的參數是不正確的,我認爲它應該接收NSButtonCell,但它正在接收NSTableView。

回答

4

顯然,發件人是您的表格視圖,但不是您特定的表格視圖單元格。

我不知道如何讓表格單元格成爲發件人,但您可以通過查找所點擊的行和列的索引來知道哪個單元格被點擊,然後您可以做出應該在單元格被點擊。

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

謝謝,這幫了很多 – 2010-03-24 19:58:30

4

在這種情況下發件人確實是一個NSTableView,但你可以檢索實際觸發事件簡單地用[發送clickedRow]和[發送clickedColumn]控制的行和列。

+1

這是最優雅的解決方案。謝謝 ! – StefanS 2015-06-04 14:52:16