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

3

6

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 ?

Agathy answered 16/11, 2011 at 9:53 Comment(1)
This is the behaviour I was actually looking for :-)Joon
W
15
[textView setTextColor:newColor];

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

Weft answered 16/11, 2011 at 10:0 Comment(2)
Brilliant. Thanks! You're right. I'd been searching through the NSTextView docs for 'color', but when I looked at the super classes I think I was searching for 'foreground'. (face palm)Agathy
Apple is so cracked out... Is it foregroundColor, textColor, NSForegroundColorAttributeName or god knows what else... I swear.. there's fewer ways to skin a cat than to change the color of type.. Except when you skin a cat, you know it's dead.. unlike choosing a way to change the color of a god-damned font, lol.Sibbie
P
3

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];
Plover answered 16/11, 2011 at 9:59 Comment(0)
C
0

This is how to do it in swift using textstorage. You can set any attribute for the text view, using this method

if let textStorage = textView.textStorage {
    let area = NSRange(location: 0, length: textStorage.length)
    textStorage.removeAttribute(.foregroundColor, range: area)
    textStorage.addAttribute(.foregroundColor, value: NSColor.yellow, range: area)
}
Caught answered 11/2, 2020 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.