简体   繁体   English

如何在NSTextView中绘制特定范围的文本的背景

[英]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 ranges of text when the user clicks on a specific part of the text view. 我有一个NSTextView,当用户单击文本视图的特定部分时,需要绘制特定范围的文本的背景。 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). 请注意,使用-setTemporaryAttributes:forCharacterRange: 设置 (而不是附加到 )给定范围的临时文本属性字典(有关附加信息,请参见-addTemporaryAttributes:forCharacterRange:

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. 在没有看到您的其余代码的情况下,我唯一能建议的就是确保这种情况发生时,您的range值正确。 Try NSLog 'ing it right before you use it and checking the log right after you've reproduced the issue. 尝试在使用NSLog之前立即对其进行记录,并在重现该问题之后立即检查日志。

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. 您可能还需要确保在将背景色设置为临时属性后,不要将其从代码中该范围的一部分中删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM