Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    }
}
like image 751
santi.gs Avatar asked Aug 08 '20 04:08

santi.gs


1 Answers

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
    }
}
like image 138
davidev Avatar answered Oct 30 '22 02:10

davidev