开发者

How to paint background of specific range of text in NSTextView

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 rang开发者_如何学编程es 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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜