因此,我有这个应用程序,我正在编写,以熟悉Swift和编程的OSX。这是一个记录应用程序。便笺窗口由一个NSTextView和一个弹出NSFontPanel的按钮组成。
更改字体效果很好。选择一个尺码?没问题。要更改字体的属性,如颜色、下划线等?我一点也不确定该怎么做。
其他来源(例如这里和这里 )似乎认为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)
}所以..。我的目标是两个:
谢谢。
发布于 2015-11-01 14:22:17
所以我确实找到了某种答案。下面是我如何在我的程序中实现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())
}
}对发送方调用convertAttributes()返回一个属性数组,但名称似乎不是NSAttributedString所要寻找的。所以我就把它们从旧名字复制到新的,然后把它们发送出去。这是一个很好的开始,但在添加属性之前,我可能会删除旧的键。
问题依然存在..。这样做对吗?
https://stackoverflow.com/questions/33438648
复制相似问题