Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a @State var from another view in SwiftUI

Tags:

state

swiftui

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?

like image 612
andrewz Avatar asked Dec 09 '25 17:12

andrewz


1 Answers

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")
    }
  }
}
like image 55
Kuhlemann Avatar answered Dec 11 '25 10:12

Kuhlemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!