9

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)
    }
}
santi.gs
  • 514
  • 3
  • 15

2 Answers2

6

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
    }
}
davidev
  • 7,694
  • 5
  • 21
  • 56
-7

Like how this looks in swift?

myNSTextField.drawsBackground = true
myNSTextField.backgroundColor = NSColor.red

What about:

struct ContentView: View {
    @State var myText: String = "blah blah blah"
    var body: some View {
        VStack(alignment: .leading) {
            TextField("Enter text", text: $myText)
            .background(Color.red)

        }.padding()
    
    }
}
Tagnal
  • 56
  • 6