Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing text selection color in NSTextView

I'm trying to write a "highlight" feature on an NSTextView. Currently, everything works great. You select a range of text and the background color of that text changes to yellow. However, while it's still selected, the background is that standard blue of selected text. How do I make that standard selection indicator color not show up in certain cases?

Thanks!

like image 775
DexterW Avatar asked Nov 29 '10 01:11

DexterW


People also ask

How do you change the selected text color?

The colour of selected text can be easily changed by using the CSS | ::selection Selector. In the below code, we have used CSS ::selection on <h1> and <p> element and set its colour as yellow with green background.

How do I change the text selection color in WordPress?

Changing the Text Selection Color in WordPressOn the left-hand admin panel, click on Appearance and select the Customize option. Click on the Additional CSS option. This will make your text selection color red. To change it, change the “FA0000” color code to the one you want.


1 Answers

Use -[NSTextView setSelectedTextAttributes:...].

For example:

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

You can simply pass an empty dictionary if you don't want the selection indicated in any way at all (short of hiding the insertion point).

Another option is to watch for selection changes and apply the "selection" using temporary attributes. Note that temporary attributes are used to show spelling and grammar mistakes and find results; so if you care about preserving these features of NSTextView then make sure only to add and remove temporary attributes, not replace them.

An example of this is (in a NSTextView subclass):

- (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];
}
like image 163
Nicholas Riley Avatar answered Sep 23 '22 02:09

Nicholas Riley