简体   繁体   中英

How does NSFontManager addFontTrait change the actual font on the UI element

I want to achieve the same thing as [[NSFontManager sharedFontManager] addFontTrait:(nullable id)sender] only using my code

The doc states

This action method causes the receiver to send its action 
message up the responder chain.
By default, the action message is changeFont:.
When a responder replies by providing a font to convert in
a convertFont: message, the receiver converts the font by 
adding the trait specified by sender. This trait is determined 
by sending a tag message to sender and interpreting it as a font 
trait mask for a convertFont:toHaveTrait: message.

so i tried

NSFontManager * fm = [NSFontManager sharedFontManager];
NSFont * font = [fm selectedFont];
NSFont * modifiedFont = [fm convertFont:font toHaveTrait:NSFontItalicTrait];
[fm setSelectedFont:modifiedFont isMultiple:YES];
[NSApp sendAction:@selector(changeFont:) to:fm.target from:fm];

or

[[self.window firstResponder] tryToPerform:@selector(changeFont:) with:modifiedFont];

but clearly i'am missing some point

How does the actual implementation in NSFontManager changes the font on the NSTextField and how can this be reproduced

Here's a slightly hacky way to do it. The Font Manager checks the sender's tag, so that just needs to match the one in the window's Edit menu

let bold = NSMenuItem()
bold.tag = 2
NSFontManager.shared.addFontTrait(bold)

This also works with an NSButton , or probably any control with a tag. This also means you can do this without writing a line of code. Just add a button in the storyboard, add NSFontManager as an object in your scene. Connect the button the the Font Manager object, and choose addFontTrait:

I haven't figured out how to de-bold this way. The window menu is able to do this.

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