views:

105

answers:

1

Hi,

This is not a specific bug, its more about not knowing how to do something.

I've an NSTextView and I need to paint the background of specific ranges of text when the user clicks on a specific part of the text view. I've tried this but I just get erratic behaviour in the sense that sometimes text loses the foreground color or the background doesn't span the whole range:

NSLayoutManager *layoutManager = [myTextView layoutManager];
[layoutManager removeTemporaryAttribute:NSBackgroundColorAttributeName
                      forCharacterRange:range];
[[myTextView layoutManager] setTemporaryAttributes:attributes 
                                 forCharacterRange:range];

For the sake of simplicity assume that range is always a valid string (it is in my testing environment).

+2  A: 

The code you posted looks correct to me.

sometimes text loses the foreground color

Is this foreground color that you're using a temporary attribute? Note that using -setTemporaryAttributes:forCharacterRange: sets (instead of appends to) the temporary text attributes dictionary for the given range (see -addTemporaryAttributes:forCharacterRange: for appending).

or the background doesn't span the whole range

Without seeing the rest of your code the only thing I can suggest is making sure that your range value is correct when this happens. Try NSLog'ing it right before you use it and checking the log right after you've reproduced the issue.

You might also want to make sure that after setting the background color into the temporary attributes you're not removing that attribute from a part of this range elsewhere in your code.

hasseg