简体   繁体   中英

Cocoa NSTextField - binding and setting attributes

  • I've got a xib with a Label (TheLabel)... which is an NSTextField. It's text is not editable by the user.
  • I have it's value bound to an NSString* in my controller class.
  • I have it's font bound to a NSFont* in my controller class.

I can change the NSString in my controller class and I see it reflected in the label.

I can change the NSFont in my controller class and I see that reflected in the label.

But...

I can't for the life of me figure out how to turn on and off underlining.

If I call this function...

-(void)setUnderlineType:(NSNumber*)underline
{
   NSMutableAttributedString* content = [[TheLabel attributedStringValue] mutableCopy];
   [content addAttribute:NSUnderlineStyleAttributeName value:underline range:NSMakeRange(0, content.length)];
   [TheLabel setAttributedStringValue:content];
}

... I get an underline, but then the bound font is ignored and I get some standard font. From then on, changing the NSFont in my controller has no visible effect on the NSTextField.

I tried removing attributes from 'content' before adding the underline... removing the font attributes... but that doesn't work either.

Any time I call this function, the font that is bound to the NSTextField become 'ignored' and I see a standard font is a standard size.

Any guidance would be greatly appreciated.

You need to set NSFontAttributeName to update a font of NSAttributedString .

NSFont *font = ...;
NSMutableAttributedString* content = [[theLabel attributedStringValue] mutableCopy];
[content addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, content.length)];
[theLabel setAttributedStringValue:content];

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