更改NstableViewCell的颜色
-
04-10-2019 - |
题
如何在NstableView中更改单元格的颜色?
解决方案
尝试使用自定义 NSView
为此,或 NSTableView
' -setBackgroundColor:
方法。
其他提示
在你的 NSTableViewDelegate
为了 NSTableView
, ,实现此方法:
- (void)tableView:(NSTableView *)tableView
willDisplayCell:(id)cell
forTableColumn:(NSTableColumn *)tableColumn
row:(NSInteger)row
这 NSTableView
在显示每个单元格之前,请在其代表上调用它,以便您可以影响其外观。假设您正在使用Nstextfieldcells,则要更改呼叫的单元格:
[cell setBackgroundColor:...];
或者,如果要更改文本颜色:
[cell setTextColor:...];
如果您希望列具有不同的外观,或者所有列不是Nstextfieldcells,请使用 [tableColumn identifier]
er,识别列。您可以通过选择表列中的接口构建器中的标识符。
//测试 - Swift 3解决方案...用于在单列中更改单元文本的颜色。我的表观视图中的所有列都有一个唯一的标识符
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let myCell:NSTableCellView = tableView.make(withIdentifier: (tableColumn?.identifier)!, owner: self) as! NSTableCellView
if tableColumn?.identifier == "MyColumn" {
let results = arrayController.arrangedObjects as! [ProjectData]
let result = results[row]
if result.ebit < 0.0 {
myCell.textField?.textColor = NSColor.red
} else {
myCell.textField?.textColor = NSColor.black
}
}
return myCell
}
//for VIEW based TableViews using Objective C
//in your NSTableViewDelegate, implement the following
//this customization makes the column numbers red if negative.
- (NSView *)tableView:(NSTableView *)inTableView
viewForTableColumn:(NSTableColumn *)tableColumn
row:(NSInteger)row
{
NSTableCellView *result = nil;
if ([tableColumn.title isEqualToString: @"Amount"]) {
//pick one of the following methods to identify the NSTableCellView
//in .xib file creation, leave identifier "blank" (default)
result = [inTableView makeViewWithIdentifier:[tableColumn identifier] owner:self];
//or set the Amount column's NSTableCellView's identifier to "Amount"
result = [inTableView makeViewWithIdentifier:@"Amount" owner:self];
id aRecord = [[arrayController arrangedObjects] objectAtIndex:row];
//test the relevant field's value
if ( aRecord.amount < 0.0 )
[[result textField] setTextColor:[NSColor colorWithSRGBRed:1.0 green:0.0 blue:0.0 alpha:1.0]];
} else {
//allow the defaults to handle the rest of the columns
result = [inTableView makeViewWithIdentifier:[tableColumn identifier] owner:self];
}
return result;
}
不隶属于 StackOverflow