Reputation: 6343
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 ?
Upvotes: 6
Views: 5052
Reputation: 46028
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];
Upvotes: 3
Reputation: 1050
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)
}
Upvotes: 0
Reputation: 7272
[textView setTextColor:newColor];
You may not have noticed that method because it is actually part of NSText, from which NSTextView inherits.
Upvotes: 15