在NSTextView中更改文本选择颜色

Dex*_*erW 11 cocoa colors highlighting highlight nstextview

我正在尝试在NSTextView上编写"突出显示"功能.目前,一切都很好.您选择一系列文本,该文本的背景颜色变为黄色.但是,虽然它仍处于选中状态,但背景是所选文本的标准蓝色.在某些情况下,如何使标准选择指示器颜色不显示?

谢谢!

Nic*_*ley 20

使用-[NSTextView setSelectedTextAttributes:...].

例如:

[textView setSelectedTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:
      [NSColor blackColor], NSBackgroundColorAttributeName,
      [NSColor whiteColor], NSForegroundColorAttributeName,
      nil]];
Run Code Online (Sandbox Code Playgroud)

如果您不希望以任何方式指示选择(没有隐藏插入点),您可以简单地传递一个空字典.

另一种选择是观察选择更改并使用临时属性应用"选择" .请注意,临时属性用于显示拼写和语法错误并查找结果; 因此,如果您关心保留NSTextView的这些功能,请确保只添加和删除临时属性,而不是替换它们.

一个例子是(在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];
}
Run Code Online (Sandbox Code Playgroud)