开发者

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

开发者 https://www.devze.com 2023-04-02 09:33 出处:网络
Is it possible to strikethrough the text in a label (NSTextField)? I have tried t开发者_开发百科o use the Font Panel, but apparently these are ignored when I try to set them:

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

I have tried t开发者_开发百科o use the Font Panel, but apparently these are ignored when I try to set them:

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

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


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


For me it works great combining the approach by sbooth of creating a custom NSTextFieldCell and overriding drawInteriorWithFrame:inView: as posted below:

- (void) drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
    [self setAttributedStringFromStringValue];
    [super drawInteriorWithFrame:cellFrame inView:controlView];
}


- (void) setAttributedStringFromStringValue {  // add strikethrough
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.stringValue];
    [attributedString addAttribute:NSStrikethroughStyleAttributeName value:(NSNumber *)kCFBooleanTrue range:NSMakeRange(0, attributedString.length)];
    [self setAttributedStringValue:attributedString];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号