在NSTextView中设置所选文本的背景颜色吗? [英] Set the background color of selected text in NSTextView?

查看:142
本文介绍了在NSTextView中设置所选文本的背景颜色吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将用户选择的一部分文本的背景色更改为另一种颜色(以添加突出显示)。现在,我尝试了:

I am trying to change the background color of a portion of text that is selected by the user to a different color (to add a highlight) to the text. Now I have tried the:


  • (void)setSelectedTextAttributes:(NSDictionary *)属性

方法,但这只会更改所选内容的背景颜色。我需要更改文本的背景颜色,以使其保持突出显示状态。

method but that only changes the background color of the selection. I need the to change the background color of text so that it stays highlighted.

推荐答案

如您所知,所选文本属性仅适用于选定的文本。如果要将某些属性添加到持久保留的选定文本中,则需要将这些属性应用于基础 NSTextStorage 对象(这只是<$ c的子类) $ c> NSMutableAttributedString )。

As you've discovered, the selected text attributes only apply to the text while it's selected. If you want to add some attributes to the selected text that persist, you'll need to apply those attributes to the underlying NSTextStorage object (which is just a subclass of NSMutableAttributedString).

执行此操作的方法是使用文本视图的 textStorage 方法,然后使用 addAttributes:range: 方法(或 setAttributes:range:取决于您要添加到现有文本属性还是完全替换它们。)

The way to do that is to use the text view's textStorage method and then apply the attributes using the addAttributes:range: method (or setAttributes:range: depending on whether you want to add to the existing text attributes or replace them altogether).

这篇关于在NSTextView中设置所选文本的背景颜色吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆