Ben
Ben

Reputation: 213

Set the background color of selected text in 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:

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.

Upvotes: 3

Views: 2137

Answers (1)

Alex
Alex

Reputation: 26859

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).

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).

Upvotes: 2

Related Questions