Question

I have a NSTextView that I want to add format buttons for (bold, italics, etc).

Right now, I have a button set to "toggle" type, with different images for on/off states.

The toggle method checks the state of the button and send the shared instance of NSFontManager.

    NSFontManager *fontManager = [NSFontManager sharedFontManager];
       if(self.writeBoldButton.state){
        [fontManager addFontTrait:sender];
       }else {
        [fontManager removeFontTrait:sender];
       }

Now I need to add code that will update the state of the button whenever the user changes the insertion point or selects a new text in the NSTextView. But how do I get the correct value?

Was it helpful?

Solution

I worked a little bit more on this after typing the question, and came up with a solution that works. Here's the code I ended up including in the NSTextView's delegate method, textViewDidChangeTypingAttributes:(NSNotification *)aNotification.

 NSFont *font = [[[self manuscriptTextView]typingAttributes]objectForKey:@"NSFont"];
   NSFontManager *fontManager = [NSFontManager sharedFontManager];

if ([fontManager traitsOfFont:font]==NSFontBoldTrait)
{
    [[self writeBoldButton]setState:1];
}else{
    [[self writeBoldButton]setState:0];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top