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

标签 cocoa nstextfield nstextview nsfontmanager

我想仅使用我的代码实现与 [[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/

相关文章:

iphone - NSPredicate 使用特殊字符过滤

objective-c - 在结束编辑时执行操作

cocoa - 如何在显示另一个属性字符串时将 NSTextField 绑定(bind)到原始字符串?

html - 将带有 CSS 的 HTML 放入 NSTextView 的简单示例?

objective-c - 你如何使用 cocoa/objective c 读取/写入/更新 m4u 和 mp3 文件元数据?

javascript - 将内容添加到 WebView 的 HTML

Cocoa,使用集合运算符和多对多关系属性进行绑定(bind)

objective-c - NSTextField 等待循环结束才更新

macos - NSTextView:何时自动插入字符(如自动匹配括号)?

cocoa - 在 NSTextView 中混合图形?