2011-11-16 103 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]; 
相關問題