Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the color of ALL text in a NSTextView (rather than just text typed afterwards)

I want to change the color of ALL the text in a NSTextView. Currently, I have code doing this:

NSMutableDictionary* fontAttributes = [[NSMutableDictionary alloc] init];
[fontAttributes setObject: newColour forKey:NSForegroundColorAttributeName];
[self setTypingAttributes:fontAttributes];  

... but that only changes the color of text typed after the attributes are set.

Is there an easy way to change the color of all text in the view, not just what is entered at the insertionPoint ?

like image 214
Graham Lea Avatar asked Nov 16 '11 09:11

Graham Lea


2 Answers

[textView setTextColor:newColor];

You may not have noticed that method because it is actually part of NSText, from which NSTextView inherits.

like image 135
Francis McGrew Avatar answered Sep 21 '22 08:09

Francis McGrew


You need to set the NSForegroundColorAttributeName attribute of the text view's NSTextStorage object:

NSTextStorage* textStorage = [textView textStorage];

//get the range of the entire run of text
NSRange area = NSMakeRange(0, [textStorage length]);

//remove existing coloring
[textStorage removeAttribute:NSForegroundColorAttributeName range:area];

//add new coloring
[textStorage addAttribute:NSForegroundColorAttributeName 
                    value:[NSColor yellowColor] 
                    range:area];
like image 42
Rob Keniger Avatar answered Sep 22 '22 08:09

Rob Keniger