Issue with NSFontPanel

393 Views Asked by At

I have an application where I user need to modify style (font, size, bold, back and fore colors,...) How can I load the initial style in the FontPanel and get the new attributes after user validation?

I tried a lot of different things but without any success.

Thanks

2

There are 2 best solutions below

1
On BEST ANSWER

Use the setPanelFont:isMultiple: to set the initially selected font.

Use [NSFontManager sharedFontManager] setSelectedAttributes:isMultiple: to change the initially colors; the dictionary keys are NSForegroundColorAttributeName and @"NSDocumentBackgroundColor" for the colors and NSUnderlineStyleAttributeName and NSStrikethroughStyleAttributeName for the styles.

When the font changes the changeFont: method of the delegate instance will be called.

Ditto styles: changeAttributes: method. And text & doc colors: setColor:forAttribute: method.

To get the new attributes in the changeAttributes method:

NSDictionary * newAttributes = [sender convertAttributes:@{}];
0
On

Swift 4.2:

NSFontPanel.shared.setPanelFont(myNSFont, isMultiple: false)
    NSFontManager.shared.setSelectedAttributes([NSAttributedString.Key.foregroundColor.rawValue: myNSColor], isMultiple: false)

You can find a list of all attribute keys here - the old style constants have not been deprecated, but as of 10.13, no longer work.

To be notified of changes if you want to change, say, the contents of a label that doesn't have a field editor attached, you need to set NSFontManager.shared's target and action, and register for NSColorPanel.colorDidChangeNotification (NSColorChanging does not fire when the ColorPanel is opened from the FontPanel).