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

发布于 2024-09-01 03:36:56 字数 503 浏览 6 评论 0原文

这不是一个特定的错误,更多的是不知道如何做某事。

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦初启 2024-09-08 03:36:56

您发布的代码对我来说看起来是正确的。

有时文本会失去前景
颜色

您使用的前景色是临时属性吗?请注意,使用 -setTemporaryAttributes:forCharacterRange: 设置(而不是附加到)给定范围的临时文本属性字典(请参阅-addTemporaryAttributes:forCharacterRange: 用于追加)。

或者背景不跨越
全系列

在没有看到代码的其余部分的情况下,我唯一可以建议的是确保发生这种情况时您的 range 值是正确的。在使用之前尝试使用 NSLog 并在重现问题后立即检查日志。

您可能还想确保在将背景颜色设置为临时属性后,您不会从代码中其他位置的该范围的一部分中删除该属性。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文