Changing TextEditor background color in SwiftUI for macOS

≯℡__Kan透↙ 提交于 2021-01-26 04:45:55

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/63311915/changing-texteditor-background-color-in-swiftui-for-macos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!