Created
July 27, 2021 14:41
-
-
Save hisavali/5b735a2dc83e7d7900528e214caad8cc to your computer and use it in GitHub Desktop.
SwiftUI: Using @binding, achieve two way state change
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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