objective-ccocoamacosnsattributedstringnscell

NSAttributedString on an NSCell


I'm filling an NSOutlineView with data that I format using NSAttributedString. So far I have formatted the text font, size and color. My problem is that the foreground color doesn't change when the row is selected. If you create an NSTextFieldCell and set the color to disabledControlTextColor on the Interface Builder, it works fine: When not selected it is show as gray, and when selected white, when I programmatically set this color to the attributed string definition it is always show as gray.

NSMutableAttributedString *result = [[[NSMutableAttributedString alloc] initWithString:value] autorelease];
NSDictionary *attributes = [[NSDictionary dictionaryWithObjectsAndKeys:
                                     [NSFont systemFontOfSize:[NSFont systemFontSize] -1], NSFontAttributeName, 
                                     [NSColor disabledControlTextColor], NSForegroundColorAttributeName, nil] retain];

[result addAttributes:attributes range:[value rangeOfString:value]];

Thanks in advance.


Solution

  • When subclassing NSCell, when setting the textfield value, we should ask if the cell isHighlighted and then set the foreground color of the text.

    NSString *titleValue = @"TEST";
    NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc] initWithString:titleValue];    
    NSColor *color = [self isHighlighted] ? [NSColor whiteColor] : [NSColor blackColor];
    NSDictionary *attributes = [[NSDictionary dictionaryWithObjectsAndKeys:
                                             [NSFont boldSystemFontOfSize:[NSFont systemFontSize] + 1], NSFontAttributeName, 
                                             color, NSForegroundColorAttributeName, nil] autorelease];
    [titleString addAttributes:attributes range:[titleValue rangeOfString:titleValue]];
    [self setAttributedStringValue:value];