在NSTableView中着色一行

Jos*_*hua 5 cocoa objective-c

我想要做的是在单击I按钮时在NSTableView中设置所选行的背景颜色.我看到那里的人使用过的其他案件tableView:willDisplayCell:forTableColumn:row:setBackgroundColor:,但我不认为这会在我的情况,我想点击一个按钮,当它发生的工作.

我知道我可以使用NSTableView的selectedRow方法找到所选行并为单元格设置背景颜色setBackgroundColor:,但我不知道该怎么办是从NSInteger获取所选行到NSCell来设置背景颜色.

Nik*_*uhe 7

NSTableViewNSCell每个列只使用一个实例.绘制内容时,将为每一行更新单元格.这就是为什么没有方法来获取指定行的单元格 - 你必须修改单元格tableView:willDisplayCell:forTableColumn:row:.

您可以告诉表视图使用只更新一行reloadDataForRowIndexes:columnIndexes:.


New*_*ack 7

将背景颜色设置为NSTableviewRow

  - (void)tableView:(NSTableView *)tableView willDisplayCell:(id)cell1 forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row 
{
      if(row==1)
         [cell1 setBackgroundColor:[NSColor redColor]];
      else if(row==2||row==3)
         [cell1 setBackgroundColor:[NSColor greenColor]];
      else
         [cell1 setBackgroundColor:[NSColor clearColor]];
}
Run Code Online (Sandbox Code Playgroud)

使用这种方法,我们可以为每一行提供不同的颜色.确保drawsBackground启用,NSTextFieldCell否则这将没有任何效果!


gre*_*use 5

如果您只想更改整个选定行的颜色:

NSInteger selectedRow = [self.nsTableView selectedRow];
NSTableRowView* rowView = [self.nsTableView rowViewAtRow:selectedRow makeIfNecessary:NO];
[rowView setBackgroundColor:[NSColor blackColor]];
Run Code Online (Sandbox Code Playgroud)

glhf

  • 仅当您使用基于视图的表时.如果我们正在谈论基于单元格的表,就像我认为的那样,那么rowViewAtRow:...方法将始终返回nil. (2认同)