I am trying to set the value of a @State var in var a of struct A from a var b of struct B, but it doesn't work. I need to use a @State var because I am passing it as a binding. Ex:
struct A : View {
@State var myBindableVar = ""
var body : some View {
TextField(self.$myBindableVar) ...
}
}
struct B : View {
@State var a : A
var body : some View {
Button(action: { self.a.myBindableVar = "???" }) { ... }
}
}
myBindableVar isn't set to "???" when the button is tapped. Why?
You need to use @Binding to achieve this. Here is some example code. I let View B appear inside View A so that you can directly see the working result on screen:
struct A : View {
@State var myBindableVar = ""
var body : some View {
VStack {
Text(myBindableVar)
Spacer()
B(myBindableVar: $myBindableVar)
}
}
}
struct B : View {
@Binding var myBindableVar : String
var body : some View {
Button(action: { self.myBindableVar = "Text appears" }) {
Text("Press to change")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With