【RichTextEditor】 【分析2】RichTextEditor设置文字内容背景色
都说AI Coder的Cursor很牛,也付费用了,
但这个背景色,搞了一天也没改过来。
最后,让它分析该控件的层次结构及文本内容显示的位置。
然后,搞定!
该自定义控件,原来文本内容设置的是按系统的外观模式色系来处理的。
结果,我在读取RTF文档后,由于文字一般都是黑色,
而我的macOS系统又是设置为深色,
结果可想而知:黑色文字,在黑色背景,基本上无法看。
我在我开发的工具软件AIBookReader中,
希望用户根据自己的喜好来设置文本内容的背景色,
所以需要提供这个修改功能。
// MARK: - Editor View
private struct EditorView: View {
@Binding var document: DemoDocument
let context: RichTextContext
@Binding var zoomScale: CGFloat
@Binding var editorViewHeight: CGFloat
let backgroundColor: Color
private let logger = Logger(subsystem: "com.demo", category: "Editor")
var body: some View {
GeometryReader { editorGeometry in
ScrollView {
RichTextEditor(
text: $document.text,
context: context
) {
textView in
// 设置 NSTextView 的背景色为当前选中的背景色
// 在这里设置文字内容的背景色 -2025-5-24-modify-by-goodmao
if let nsTextView = textView as? NSTextView {
//nsTextView.backgroundColor = NSColor(backgroundColor)
nsTextView.backgroundColor = NSColor.cyan
}
}
.frame(minHeight: editorGeometry.size.height)
.scaleEffect(zoomScale, anchor: .topLeading)
.frame(width: editorGeometry.size.width, height: editorGeometry.size.height, alignment: .topLeading)
.border(Color.red, width: 2)
.onChange(of: zoomScale) { oldValue, newValue in
let scaledWidth = editorGeometry.size.width * newValue
let scaledHeight = editorGeometry.size.height * newValue
logger.info("缩放区域尺寸变化 - 宽度: \(scaledWidth), 高度: \(scaledHeight), 缩放比例: \(newValue)")
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onChange(of: editorGeometry.size) { oldValue, newValue in
editorViewHeight = newValue.height
logger.info("=== 【红色区域】:编辑区域和缩放控件-VStack 中的 RichTextEditor 高度: \(newValue.height)")
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}