3

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?

andrewz
  • 4,729
  • 5
  • 49
  • 67
  • [Understanding @State and @Binding](https://stackoverflow.com/questions/56488929/understanding-binding-in-swiftui)... and search by keywords. – Asperi Apr 21 '20 at 03:20

1 Answers1

4

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")
    }
  }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Kuhlemann
  • 3,066
  • 3
  • 14
  • 41