Search code examples
swiftmacosswiftuinstextfield

Changing TextEditor background color in SwiftUI for macOS


I would like to change the background color of a SwiftUI text editor on macOS. Is there a variant for the code below (used for iOS) to work for NSTextField instead of UITextView?

Thanks.

struct ContentView: View {
    init() {
        UITextView.appearance().backgroundColor = .clear
    }

    var body: some View {
        TextEditor(text: .constant("Placeholder"))
            .background(Color.red)
    }
}

Solution

  • I have just posted an answer for that issue on a similar question here

    With the help of extension, you can clear the default background Color of the NSTextView class and then use .background modifier in SwiftUI like this

    extension NSTextView {
        open override var frame: CGRect {
            didSet {
                backgroundColor = .clear //<<here clear
                drawsBackground = true
            }
    
        }
    }
    
    struct ContentView: View {
        
        @State var string: String = ""
        
        var body: some View {
            TextEditor(text: $string)
                .textFieldStyle(PlainTextFieldStyle())
                .background(Color.red) //<< here red
        }
    }