Skip to content

Instantly share code, notes, and snippets.

@hisavali
Created July 27, 2021 14:41
Show Gist options
  • Save hisavali/5b735a2dc83e7d7900528e214caad8cc to your computer and use it in GitHub Desktop.
Save hisavali/5b735a2dc83e7d7900528e214caad8cc to your computer and use it in GitHub Desktop.
SwiftUI: Using @binding, achieve two way state change
import SwiftUI
struct BadgeView: View {
@Binding var viewstate: String
var body: some View {
VStack {
Text(viewstate)
.padding()
Button("Tap: Child to parent") {
// Change made by child entity
self.$viewstate.wrappedValue = "Hello (Child) \(Int.random(in: 0...10))"
}
}
}
}
struct Wrapper: View {
@State var parentstate: String = "Hello (initial)"
var body: some View {
VStack {
Spacer()
BadgeView(viewstate: self.$parentstate)
Spacer()
Button("Tap: Parent to Child") {
// Change made by Parent entity
parentstate = "Hello (Parent) \(Int.random(in: 0...10))"
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Wrapper()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment