I created a simple TextView
like this:
import SwiftUI
struct TextView: UIViewRepresentable {
@Binding var inputText: String
func makeUIView(context: UIViewRepresentableContext<Self>) -> UITextView {
return UITextView()
}
func updateUIView(_ uiView: UITextView, context: Context) {
// uiView.text = self.inputText
self.inputText = uiView.text
}
}
And the main view contains a variable with a @State
wrapper.
import SwiftUI
struct Test: View {
@State private var inputText: String = ""
var body: some View {
VStack {
TextEditor(text: $inputText)
TextView(inputText: $inputText)
}
}
}
struct Test_Previews: PreviewProvider {
static var previews: some View {
Test()
}
}
As I understand, the TextView
and TextEditor
are connected by this inputText
, who has a @Binding
wrapper in the definition of TextView
. Thus if I type in one of them, another should show the same text. However, to my surprise, the text in these two are completely separated with each other.
If I change the self.inputText = uiView.text
to uiView.text = self.inputText
, then when I type in TextEditor
, the TextView
would show the same text, but if I type in TextView
, then nothing happens in TextEditor
.
Why does this happen?