当用户在您的 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.
}
}
我根本没有测试或尝试过这段代码,但这应该能让你到达你需要的地方。