代码之家  ›  专栏  ›  技术社区  ›  Dexter

在NSTextView中更改文本选择颜色

  •  10
  • Dexter  · 技术社区  · 15 年前

    我正试图在NSTextView上编写一个“highlight”特性。现在,一切都很好。选择一个文本区域,该文本的背景颜色将变为黄色。但是,当它仍然处于选中状态时,背景是所选文本的标准蓝色。如何使标准选择指示器的颜色在某些情况下不显示?

    谢谢!

    1 回复  |  直到 15 年前
        1
  •  20
  •   Nicholas Riley    15 年前

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

    例如:

    [textView setSelectedTextAttributes:
         [NSDictionary dictionaryWithObjectsAndKeys:
          [NSColor blackColor], NSBackgroundColorAttributeName,
          [NSColor whiteColor], NSForegroundColorAttributeName,
          nil]];
    

    如果您根本不希望以任何方式指示所选内容(除了隐藏插入点之外),只需传递一个空字典。

    另一个选项是监视选择更改并使用 temporary attributes . 请注意,临时属性用于显示拼写和语法错误并查找结果;因此,如果要保留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];
    }