當用戶在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.
}
}
我沒有測試或試用這個代碼在所有的,但這應該讓你到你需要的人。