简体   繁体   中英

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.

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];

use this in the custom cell, i tried everything on the internet and finally below thing worked

- (void)updateCellDisplay {
  if (self.selected || self.highlighted) {
  self.nameLabel.textColor = [UIColor lightGrayColor];
  self.colorLabel.textColor = [UIColor lightGrayColor];
  }
  else {
   self.nameLabel.textColor = [UIColor blackColor];
   self.colorLabel.textColor = [UIColor blackColor];
  }
}

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
  [super setHighlighted:highlighted animated:animated];
  [self updateCellDisplay];
}

- (void) setSelected:(BOOL)selected animated:(BOOL)animated {
  [super setSelected:selected animated:animated];
  [self updateCellDisplay];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM