首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSTextView、NSFontManager和changeAttributes()

NSTextView、NSFontManager和changeAttributes()
EN

Stack Overflow用户
提问于 2015-10-30 14:44:22
回答 1查看 1K关注 0票数 1

因此,我有这个应用程序,我正在编写,以熟悉Swift和编程的OSX。这是一个记录应用程序。便笺窗口由一个NSTextView和一个弹出NSFontPanel的按钮组成。

更改字体效果很好。选择一个尺码?没问题。要更改字体的属性,如颜色、下划线等?我一点也不确定该怎么做。

其他来源(例如这里这里 )似乎认为NSTextView应该是NSFontManager的目标,而NSTextView有自己的changeAttributes()实现。然而,让NSTextView成为目标却什么也做不了。当我在NSTextView中选择文本并打开字体面板时,我在fontPanel中所做的第一个选择将导致文本的取消选择。

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

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

以下是相关代码:

代码语言:javascript
复制
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
}

更改字体的代码。这个很好用。

代码语言:javascript
复制
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的存根代码:

代码语言:javascript
复制
func changeAttributes(sender: AnyObject) {
    print(sender)
}

所以..。我的目标是两个:

  1. 明白这是怎么回事
  2. 将我在fontPanel中所做的任何更改反映在NSTextView选定的文本中。

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2015-11-01 14:22:17

所以我确实找到了某种答案。下面是我如何在我的程序中实现changeAttributes():

代码语言:javascript
复制
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所要寻找的。所以我就把它们从旧名字复制到新的,然后把它们发送出去。这是一个很好的开始,但在添加属性之前,我可能会删除旧的键。

问题依然存在..。这样做对吗?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33438648

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档