【RichTextEditor】 【分析2】RichTextEditor设置文字内容背景色

【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)
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值