我有一个
NSTExtView
,并且正在使用 [theTextView.textStorage addAttribute: value: range:]
为某些文本范围设置属性
例如,我使用
[theTextView.textStorage addAttribute:NSBackgroundColorAttributeName value:[NSColor yellowColor] range:theSelectedRange];
突出显示一个范围
问题是,当我在该范围内手动输入新文本时,它不会突出显示。它将突出显示的范围分为 2 个范围,并在它们之间插入非突出显示的文本。有没有办法让新插入的文本也高亮显示?
当用户在 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.
}
}
我根本没有测试或尝试过这段代码,但这应该可以让你到达你需要的地方。
你基本上必须设置 NSTextView 的打字属性。
为此,您可以使用 NSTextViewDelegate 中存在的
textViewDidChangeSelection
方法来监听插入符号的移动。更新 textView 的打字属性
func textViewDidChangeSelection(_ notification: Notification) {
if let attrs = textView.textStorage?.attributes(at: textView.selectedRange().location, effectiveRange: nil) {
textView.typingAttributes = attrs
}
}