问题
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