我想仅使用我的代码实现与 [[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 上的字体以及如何重现
最佳答案
这里有一个稍微有点老套的方法。字体管理器检查发送者的标签,因此只需与窗口的编辑
菜单中的标签匹配
let bold = NSMenuItem()
bold.tag = 2
NSFontManager.shared.addFontTrait(bold)
这也适用于 NSButton
,或者任何带有标签的控件。这也意味着您无需编写一行代码即可完成此操作。只需在 Storyboard中添加一个按钮,将 NSFontManager
添加为场景中的对象即可。将按钮连接到 Font Manager 对象,然后选择 addFontTrait:
我还没有弄清楚如何以这种方式去粗体。窗口菜单可以做到这一点。
关于cocoa - NSFontManager addFontTrait 如何更改 UI 元素上的实际字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38857904/