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.



Subscribe
Notify of
guest

5 Comments
Inline Feedbacks
View all comments
Anonymous Coward

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

corbin

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

Enrique

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!

Subscribe to new posts:

You'll get an email whenever a I publish a new post to my blog and nothing more. -- Corbin

As an Amazon Associate I earn from qualifying purchases.

(c) 2008-2024 Corbin Dunn

Privacy Policy

Subscribe to RSS feeds for entries.

71 queries. 0.221 seconds.

Log in