How ca开发者_如何学Pythonn I change the color of a cell in my NSTableView?
In your NSTableViewDelegate
for the NSTableView
, implement this method:
- (void)tableView:(NSTableView *)tableView
willDisplayCell:(id)cell
forTableColumn:(NSTableColumn *)tableColumn
row:(NSInteger)row
The NSTableView
calls this on its delegate before displaying each cell so that you can affect its appearance. Assuming you're using NSTextFieldCells, for the cell that you want to change call:
[cell setBackgroundColor:...];
Or, if you want to change the text color:
[cell setTextColor:...];
If you want columns to have different appearances, or if all of the columns aren't NSTextFieldCells, use [tableColumn identifier]
to, er, identify the column. You can set the identifier in Interface Builder by selecting the table column.
// TESTED - Swift 3 solution...for changing color of cell text in a single column. All columns in my tableview have a unique identifier
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;
}
Try using a custom NSView
for that, or NSTableView
's -setBackgroundColor:
method.
精彩评论