gpt4 book ai didi

objective-c - 如何在背景窗口上设置 [NSTextView selectedTextAttributes]?

转载 作者:太空狗 更新时间:2023-10-30 03:31:21 32 4
gpt4 key购买 nike

[NSTextView selectedTextAttributes] 的默认值在我的应用中不可用,因为我允许用户选择几乎与背景颜色完全相同的颜色(语法高亮显示)。

我已经写了一些数学来确定合适的颜色并可以用它来设置它:

textView.selectedTextAttributes = @{
NSBackgroundColorAttributeName: [NSColor yellowColor],
NSForegroundColorAttributeName: [NSColor redColor]
};

但是当窗口处于后台时,它仍然使用系统默认的浅灰色。

我附上了上述代码的屏幕截图以及事件窗口和非事件窗口。 — 如何更改非事件窗口的选定文本背景颜色?

active inactive

最佳答案

您可以通过覆盖NSLayoutManager 的绘制方法来覆盖颜色。

final class LayoutManager1: NSLayoutManager {
override func fillBackgroundRectArray(rectArray: UnsafePointer<NSRect>, count rectCount: Int, forCharacterRange charRange: NSRange, color: NSColor) {
let color1 = color == NSColor.secondarySelectedControlColor() ? NSColor.redColor() : color
color1.setFill()
super.fillBackgroundRectArray(rectArray, count: rectCount, forCharacterRange: charRange, color: color1)
color.setFill()
}
}

并将 NSTextView 的布局管理器替换为它。

textView.textContainer!.replaceLayoutManager(layoutManager1)

这是 full working example .


当@Kyle 询问setFill 的原因时,我添加了一些更新。

来自苹果手册:

... the charRange and color parameters are passed in merely for informational purposes; the color is already set in the graphics state. If for any reason you modify it, you must restore it before returning from this method. ...

这意味着将其他颜色传入 super 调用没有效果,你只需要NSColor.setFill 使其与 super 调用一起工作。另外,手册要求将其设置回原来的。

关于objective-c - 如何在背景窗口上设置 [NSTextView selectedTextAttributes]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16073233/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com