cocoamacosinterface-buildernstextfieldstrikethrough

Mac OS X: strikethrough the text in a label (NSTextField)


Is it possible to strikethrough the text in a label (NSTextField)?

I have tried to use the Font Panel, but apparently these are ignored when I try to set them:

enter image description here

enter image description here


Solution

  • You can do it like this, assuming _textField is set as an outlet in your xib:

    - (void) awakeFromNib
    {
      NSMutableAttributedString *as = [[_textField attributedStringValue] mutableCopy];
      [as addAttribute:NSStrikethroughStyleAttributeName value:(NSNumber *)kCFBooleanTrue range:NSMakeRange(0, [as length])];
      [_textField setAttributedStringValue:[as autorelease]];
    }
    

    Edit:

    If you want to write a custom strikethrough NSTextFieldCell subclass instead, the only method that should be necessary to override is setStringValue:

    - (void) setStringValue:(NSString *)aString
    {
      NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithString:aString];
      [as addAttribute:NSStrikethroughStyleAttributeName value:(NSNumber *)kCFBooleanTrue range:NSMakeRange(0, [as length])];
      [self setAttributedStringValue:[as autorelease]];
    }