I am trying to wrap a NSTextView in a NSViewRepresentable SwiftUI view.
If text is changed, then updateNSView is called, and the view is correctly updated, but how do I do it the other way around?
I want text to be updated when the user types in the NSTextView and I cannot figure out how to do this. The TextView needs a delegate to handle text changed, but the NSViewRepresentable view cannot implment this protocol (because it is not a class).
I have a simple ContentView below that illustrates my problem. It contains Text, my TextView and a TextField. All three use the same text binding. If you type in the TextField, then Text and my TextView is updated, but when you type in my TextView, it does not update text, and hence nothing happens. How can I let my TextView work like TextField?
struct TextView: NSViewRepresentable {
typealias NSViewType = NSTextView
@Binding var text: String
func makeNSView(context: Self.Context) -> Self.NSViewType {
let view = NSTextView()
return view
}
func updateNSView(_ nsView: Self.NSViewType, context: Self.Context) {
nsView.string = text
}
}
struct ContentView: View {
@State var text: String = ""
var body: some View {
VStack {
Text(text)
Divider()
TextField("", text: $text)
TextView(text: $text)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
}