Corbin Dunn
Redwood Monkey

Cocoa: willDisplayCell delegate method of NSTableView, [NSCell setTextColor], and “source lists”

Apple, Cocoa, Coding

Mac OS 10.5 added a “source list” highlighting style to NSTableView, with the API below for your reference:

enum {

NSTableViewSelectionHighlightStyleRegular = 0,

NSTableViewSelectionHighlightStyleSourceList = 1,

};

typedef NSInteger NSTableViewSelectionHighlightStyle;

– (NSTableViewSelectionHighlightStyle)selectionHighlightStyle;

– (void)setSelectionHighlightStyle:(NSTableViewSelectionHighlightStyle)selectionHighlightStyle;


Source lists should have bold text when the item is selected, and NSTableView attempts to auto-format the cell’s contents to automatically do this for you, as seen in this screen shot for the selected item in the open panel source list:

However, the code that does this formatting does so by converting the ‘stringValue’ of the cell to an attributedStringValue that has the bold text. This is done *before* calling the delegate with “willDisplayCell”. The delegate gets the final say of how it looks in “willDisplayCell”, but this can cause unexpected results if you want to do something like this:

– (void)tableView:(NSTableView *)tableView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {

if(row == 0) {

[cell setTextColor: [NSColor redColor]];

} else {

[cell setTextColor: [NSColor blackColor]];

}

}

The problem with the above code is that it is *too late* for the coloring to be correctly applied to the cell if it is selected. The work around is easy; you need to color the cell text earlier, and a perfect place to do that is in the new 10.5 delegate method “dataCellForTableColumn:”

– (NSCell *)tableView:(NSTableView *)tableView dataCellForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {

NSTextFieldCell *cell = [tableColumn dataCell];

if(row == 0) {

[cell setTextColor: [NSColor redColor]];

} else {

[cell setTextColor: [NSColor blackColor]];

}

return cell;

}

Cool. Have fun.

Previous Post
no_thumbnail
Silk instruction
Next Post
no_thumbnail
Artisan Tree & Treehouse

5
Leave a Reply

avatar
500
5 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
EnriquecorbinAnonymous Cowardcorbin Recent comment authors
  Subscribe  
Notify of
Anonymous Coward
Guest
Anonymous Coward

Hmm, that’s not really cool. That’s a bug that should be fixed by Apple.

corbin
Guest

another work around would be to return an attributed string from the datasource method that included the appropriate colors.

Enrique
Guest

How about changing the background color of the cell? I tried with [cell setBackgroundColor:] and didn’t work (it works well for the cell text as you described.

Thanks!

(c) 2008-2018 Corbin Dunn

Privacy Policy

Subscribe to RSS feeds for entries.

81 queries. 0.392 seconds.

Log in