Created
December 15, 2021 22:43
-
-
Save SaganRitual/c87debe6c6e3ee1661d99fff45a5569a to your computer and use it in GitHub Desktop.
One way of passing state from parent to child
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
// 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