NSFontManager addFontTrait如何更改UI元素上的实际字体

问题描述 投票:7回答:1

我只想使用我的代码来实现与[[NSFontManager sharedFontManager] addFontTrait:(nullable id)sender]相同的功能

文档状态

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.

所以我尝试过

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

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

但很明显,我缺少了一点

NSFontManager中的实际实现如何更改NSTextField上的字体以及如何复制它]]

我只想使用我的代码来实现与[[NSFontManager sharedFontManager] addFontTrait:(nullable id)sender]相同的功能doc状态此操作方法使接收方发送其操作...]]

cocoa nstextfield nstextview nsfontmanager
1个回答
1
投票
这是一种有点怪癖的方式。字体管理器检查发送者的标签,因此只需要匹配窗口的Edit菜单中的标签即可。>

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

这也适用于NSButton,或带有标签的任何控件。这也意味着您无需编写代码即可执行此操作。只需在情节提要中添加一个按钮,然后将NSFontManager添加为场景中的对象即可。将按钮连接到字体管理器对象,然后选择addFontTrait:
© www.soinside.com 2019 - 2024. All rights reserved.