Thursday, October 1, 2009

Table view colored text



Suppose you have a table view and you want to make a simple change to how the data is displayed. For example, in my checkbook application, I show the amount for a check in red text, while deposits are black as usual.

To do that without bindings, a simple way is to implement this method in the table view's delegate:

- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex

For example, you could do:

if ([[tc identifier] isEqualToString:@"amount"]){
NSParameterAssert(i >= 0 && i < [dataArray count]);
D = [dataArray objectAtIndex:i];
if ([[D objectForKey:@"deposit"] boolValue]) {
[aCell setTextColor:black];
}
else {
[aCell setTextColor:red];
}
}


If the default behavior is fine, you don't have to do anything for that table column. But for any particular column, if you change one cell, you have to change them all:

To quote the docs:

Because aCell is reused for every row in aTableColumn, the delegate must set the display attributes both when drawing special cells and when drawing normal cells.


You can also use this approach to set images for cells, if the column uses an NSImageCell.