如何在 NSTextView 中绘制特定范围文本的背景
这不是一个特定的错误,更多的是不知道如何做某事。
我有一个 NSTextView,当用户单击文本视图的特定部分时,我需要绘制特定文本范围的背景。我已经尝试过这个,但我只是得到了不稳定的行为,因为有时文本会丢失前景色或背景不跨越整个范围:
NSLayoutManager *layoutManager = [myTextView layoutManager];
[layoutManager removeTemporaryAttribute:NSBackgroundColorAttributeName
forCharacterRange:range];
[[myTextView layoutManager] setTemporaryAttributes:attributes
forCharacterRange:range];
为了简单起见,假设范围始终是一个有效的字符串(它在我的测试环境)。
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您发布的代码对我来说看起来是正确的。
您使用的前景色是临时属性吗?请注意,使用
-setTemporaryAttributes:forCharacterRange:
设置(而不是附加到)给定范围的临时文本属性字典(请参阅-addTemporaryAttributes:forCharacterRange:
用于追加)。在没有看到代码的其余部分的情况下,我唯一可以建议的是确保发生这种情况时您的
range
值是正确的。在使用之前尝试使用 NSLog 并在重现问题后立即检查日志。您可能还想确保在将背景颜色设置为临时属性后,您不会从代码中其他位置的该范围的一部分中删除该属性。
The code you posted looks correct to me.
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).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. TryNSLog
'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.