设置TextEditorbackground会发现并不能改变其背景色,因为颜色在TextEditor内部的TextView上,因此可以使用extension把所有的TextViewbackground设置为.clear把背景色清除。
然后再使用.background就可以成功设置TextEditor的背景色。

import SwiftUI

extension NSTextView {
    open override var frame: CGRect {
        didSet {
            backgroundColor = .clear // 清除TextView背景颜色
            drawsBackground = true
        }

    }
}

struct ContentView: View {
    
    @State var string: String = "这是一个文本编辑器"
    
    var body: some View {
        TextEditor(text: $string)
            .textFieldStyle(PlainTextFieldStyle())
            .background(Color.blue) // 设置背景颜色
    }
}

macOSSwiftUI

5 条评论

  1. bidzrbxvdz
    2025-03-04 19:47
    回复

    文章深入浅出,既有深度思考,又不乏广度覆盖,令人叹为观止。

  2. jmxxwuastw
    2025-03-03 02:09
    回复

    结论部分可提出实际应用建议,提升价值。

  3. phfgopznla
    2025-03-02 21:30
    回复

    作者的才华横溢,让这篇文章成为了一篇不可多得的艺术品。

  4. vihqzvcuwx
    2024-09-22 18:50
    回复

    博主真是太厉害了!!!

  5. 跨境电商B2B系统
    2023-10-11 10:06
    回复

    感谢分享

添加新评论