【问题标题】:How does NSFontManager addFontTrait change the actual font on the UI elementNSFontManager addFontTrait如何改变UI元素上的实际字体
【发布时间】:2016-08-09 18:25:01
【问题描述】:

我想仅使用我的代码实现与[[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 上的字体以及如何重现

【问题讨论】:

    标签: cocoa nstextfield nstextview nsfontmanager


    【解决方案1】:

    这里有一个稍微老套的方法。字体管理器检查发件人的标签,因此只需要匹配窗口的Edit 菜单中的标签

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

    这也适用于NSButton,或者任何带有标签的控件。这也意味着您无需编写任何代码就可以做到这一点。只需在情节提要中添加一个按钮,将NSFontManager 添加为场景中的对象。连接字体管理器对象的按钮,并选择addFontTrait:

    我还没有弄清楚如何以这种方式去除粗体。窗口菜单能够做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-25
      • 2011-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多