【问题标题】:NSTextView, NSFontManager, and changeAttributes()NSTextView、NSFontManager 和 changeAttributes()
【发布时间】:2015-10-30 14:44:22
【问题描述】:

所以我写了这个应用程序来熟悉 Swift 和 OSX 编程。这是一个笔记应用程序。笔记窗口由一个 NSTextView 和一个可以调出 NSFontPanel 的按钮组成。

更改字体效果很好。选择尺码?没问题。想要更改字体的属性,如颜色、下划线等?我完全不确定如何让它发挥作用。

其他来源(例如herehere)似乎建议NSTextView 应该是NSFontManager 的目标,并且NSTextView 有它自己的changeAttributes() 实现。然而,使 NSTextView 成为目标,什么也没做。当我在 NSTextView 中选择文本并调出字体面板时,我在 fontPanel 中所做的第一次选择会导致取消选择文本。

使我的视图控制器成为 NSFontManager 的目标并为 changeAttributes 实现一个存根会产生一个 NSFontEffectsBox 类型的对象,我找不到任何好的文档。

问题是……我应该用 NSFontEffectsBox 做什么?如果在 fontPanel 中我选择带有双下划线的蓝色文本,我可以在调试器中看到这些属性,但我无法以编程方式访问它们。

以下是相关代码:

override func viewDidLoad() {
    super.viewDidLoad()
    loadNoteIntoInterface()
    noteBody.keyDelegate = self  // noteBody is the NSTextView
    noteBody.delegate = self
    noteBody.usesFontPanel = true
    fontManager = NSFontManager.sharedFontManager()
    fontManager!.target = self
}

更改字体的代码。这工作得很好。

override func changeFont(sender: AnyObject?) {
    let fm = sender as! NSFontManager
    if noteBody.selectedRange().length>0 {
        let theFont = fm.convertFont((noteBody.textStorage?.font)!)
        noteBody.textStorage?.setAttributes([NSFontAttributeName: theFont], range: noteBody.selectedRange())
    }
}

changeAttributes 的存根代码:

func changeAttributes(sender: AnyObject) {
    print(sender)
}

所以.. 我的目标有两个:

  1. 了解这里发生了什么
  2. 我在 fontPanel 中所做的任何更改都会反映在 NSTextView 选定的文本中。

谢谢。

【问题讨论】:

    标签: swift macos nstextview nsfontmanager nsfontpanel


    【解决方案1】:

    所以我确实设法找到了某种答案。以下是我在程序中实现 changeAttributes() 的方式:

    func changeAttributes(sender: AnyObject) {
        var newAttributes = sender.convertAttributes([String : AnyObject]())
        newAttributes["NSForegroundColorAttributeName"] = newAttributes["NSColor"]
        newAttributes["NSUnderlineStyleAttributeName"] = newAttributes["NSUnderline"]
        newAttributes["NSStrikethroughStyleAttributeName"] = newAttributes["NSStrikethrough"]
        newAttributes["NSUnderlineColorAttributeName"] = newAttributes["NSUnderlineColor"]
        newAttributes["NSStrikethroughColorAttributeName"] = newAttributes["NSStrikethroughColor"]
    
        print(newAttributes)
    
        if noteBody.selectedRange().length>0 {
            noteBody.textStorage?.addAttributes(newAttributes, range: noteBody.selectedRange())
        }
    }
    

    在 sender 上调用 convertAttributes() 会返回一个属性数组,但名称似乎不是 NSAttributedString 正在寻找的。所以我只是将它们从旧名称复制到新名称并发送。这是一个好的开始,但我可能会在添加属性之前删除旧键。

    问题仍然存在,但是……这是正确的做事方式吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多