gpt4 book ai didi

swift - NSTextView、NSFontManager 和 changeAttributes()

转载 作者:行者123 更新时间:2023-11-28 06:56:43 26 4
gpt4 key购买 nike

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

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

其他来源(例如 herehere)似乎表明 NSTextView 应该是 NSFontManager 的目标并且 NSTextView 有它自己的 changeAttributes() 实现。然而,将 NSTextView 设为目标并没有任何作用。当我在 NSTextView 中选择文本并调出字体面板时,我在 fontPanel 中所做的第一个选择会导致取消选择文本。

使我的 View Controller 成为 NSFontManager 的目标并为 changeAttributes 实现一个 stub 会产生一个 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 stub 代码:

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

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

  1. 了解这里发生了什么
  2. 让我在 fontPanel 中所做的任何更改反射(reflect)在 NSTextView 所选文本中。

谢谢。

最佳答案

所以我确实设法找到了某种答案。以下是我在我的程序中实现 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 正在寻找的。所以我只是将它们从旧名称复制到新名称并继续发送。这是一个好的开始,但我可能会在添加属性之前删除旧 key 。

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

关于swift - NSTextView、NSFontManager 和 changeAttributes(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33438648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com