2011-11-16 21 views
4

我想更改NSTextView中所有文本的颜色。 目前,我有代码这样做:如何设置NSTextView中的所有文本的颜色(而不仅仅是之后输入的文本)

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

...但是,只有改变属性设置后,输入文本的颜色。

是否有一种简单的方法来改变视图中所有文本的颜色,而不仅仅是在插入点处输入的内容?

+1

这是我实际上正在寻找的行为:-) – markhunte

回答

11
[textView setTextColor:newColor]; 

你可能没有注意到的方法,因为它实际上是NSText,从NSTextView继承的一部分。

+0

辉煌。谢谢!你是对的。我一直在通过NSTextView文档搜索“颜色”,但是当我看着超类时,我想我正在寻找'前景'。 (脸掌) –

+0

苹果是如此破裂......它是'foregroundColor','textColor','NSForegroundColorAttributeName'或_god知道还有什么_...我发誓..皮肤猫的方法比改变颜色更少的类型..除了当你皮肤的猫,你知道它已经死了..不同于选择一种方式来改变_god-damned_字体的颜色,哈哈。 –

2

您需要设置文本视图的NSTextStorage对象的属性NSForegroundColorAttributeName

NSTextStorage* textViewContent = [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]; 
相关问题