2012-08-06 21 views
0

我有一個NSTExtView並使用[theTextView.textStorage addAttribute: value: range:]NSTextView不將屬性應用於新插入的文本

例如是文本的一定範圍設置attribues,我突出使用[theTextView.textStorage addAttribute:NSBackgroundColorAttributeName value:[NSColor yellowColor] range:theSelectedRange];

問題的範圍是,當我手動鍵入新的文本到該範圍內,它不會突出顯示。它將突出顯示的範圍分成2個範圍,並在它們之間插入非高亮文本。有沒有辦法讓新插入的文本也被突出顯示?

回答

0

當用戶在NSTextView中鍵入新內容時,插入點將使用與當前字體關聯的任何屬性(如果有的話)。這也被稱爲文本視圖的「typingAttributes」。在大多數情況下,用戶將以黑色和白色背景進行打字。

現在,由於您正在突出顯示(而不是進行選擇),因此您需要做的是在光標的插入點處拾取當前顏色。

你可以做到這一點通過通過獲取的屬性:

// I think... but am not 100% certain... the selected range 
// is the same as the insertion point. 
NSArray * selectedRanges = [theTextView selectedranges]; 
if(selectedRanges && ([selectedRanges count] > 0)) 
{ 
    NSValue * firstSelectionRangeValue = [selectedRanges objectAtIndex: 0]; 
    if(firstSelectionRangeValue) 
    { 
     NSRange firstCharacterOfSelectedRange = [firstSelectionRangeValue rangeValue]; 

     // now that we know where the insertion point is likely to be, let's get 
     // the attributes of our text 
     NSSDictionary * attributesDictionary = [theTextView.textStorage attributesAtIndex: firstCharacterOfSelectedRange.location effectiveRange: NULL]; 

     // set these attributes to what is being typed 
     [theTextView setTypingAttributes: attributesDictionary]; 

     // DON'T FORGET to reset these attributes when your selection changes, otherwise 
     // your highlighting will appear anywhere and everywhere the user types. 
    } 
} 

我沒有測試或試用這個代碼在所有的,但這應該讓你到你需要的人。

相關問題