Cocoa 在NSTextView中更改文本选择颜色

Cocoa 在NSTextView中更改文本选择颜色,cocoa,colors,highlighting,highlight,nstextview,Cocoa,Colors,Highlighting,Highlight,Nstextview,我正在尝试在NSTextView上编写一个“突出显示”功能。目前,一切都很好。选择一个文本范围,该文本的背景色将变为黄色。然而,当它仍然处于选中状态时,背景是所选文本的标准蓝色。如何使标准选择指示器颜色在某些情况下不显示 谢谢 使用 例如: [textView setSelectedTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys: [NSColor blackColor], NSBackgroundCol

我正在尝试在NSTextView上编写一个“突出显示”功能。目前,一切都很好。选择一个文本范围,该文本的背景色将变为黄色。然而,当它仍然处于选中状态时,背景是所选文本的标准蓝色。如何使标准选择指示器颜色在某些情况下不显示

谢谢

使用

例如:

[textView setSelectedTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:
      [NSColor blackColor], NSBackgroundColorAttributeName,
      [NSColor whiteColor], NSForegroundColorAttributeName,
      nil]];
如果您根本不希望以任何方式指示选择(除了隐藏插入点),您可以简单地传递一个空字典

另一个选项是监视选择的更改,并使用应用“选择”。请注意,临时属性用于显示拼写和语法错误并查找结果;因此,如果您想保留NSTextView的这些功能,请确保只添加和删除临时属性,而不是替换它们

例如(在NSTextView子类中):


通过将背景色设置为clearColor,高光仅在整个选择完成后工作。如何在选择过程中应用这些属性?只有释放鼠标按钮(即,您不再
仍在选择
),才会发送通知。如果您想处理正在进行的选择,您需要子类NSTextView(编辑我的答案以提供一些示例代码)。
- (void)setSelectedRanges:(NSArray *)ranges affinity:(NSSelectionAffinity)affinity stillSelecting:(BOOL)stillSelectingFlag;
{
    NSArray *oldRanges = [self selectedRanges];
    for (NSValue *v in oldRanges) {
        NSRange oldRange = [v rangeValue];
        if (oldRange.length > 0)
            [[self layoutManager] removeTemporaryAttribute:NSBackgroundColorAttributeName forCharacterRange:oldRange];
    }

    for (NSValue *v in ranges) {
        NSRange range = [v rangeValue];
        if (range.length > 0)
            [[self layoutManager] addTemporaryAttributes:[NSDictionary dictionaryWithObject:[NSColor blueColor] forKey:NSBackgroundColorAttributeName]
                                       forCharacterRange:range];
    }

    [super setSelectedRanges:ranges affinity:affinity stillSelecting:stillSelectingFlag];
}