Skip to content

Instantly share code, notes, and snippets.

@SaganRitual
Created December 15, 2021 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SaganRitual/c87debe6c6e3ee1661d99fff45a5569a to your computer and use it in GitHub Desktop.
Save SaganRitual/c87debe6c6e3ee1661d99fff45a5569a to your computer and use it in GitHub Desktop.
One way of passing state from parent to child
// We are a way for the cosmos to know itself. -- C. Sagan
import SwiftUI
class ChildState: ObservableObject {
@Published var childData = 0
}
struct Parent: View {
@State var parentData = 0
var body: some View {
ZStack {
Color.black
VStack {
Text("Parent state \(parentData) -- click me")
.onTapGesture {
parentData += 1
}
Child(parentData: parentData, childState: ChildState())
}
}
}
}
struct Child: View {
let parentData: Int
@StateObject var childState: ChildState
var body: some View{
Text("Child state \(childState.childData) parentState \(parentData) -- click me")
.onTapGesture {
childState.childData += 1
}
}
}
struct ContentView: View {
var body: some View {
Parent()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment