๐ฅStateObject
SwiftUI โฉ Data Flow โฉ StateObject
๐ ๅ่๏ผSwift Playgrounds (Keep Going with Apps) - Sharing Data Between Views.
๐ CreatureZoo
// โญ๏ธ 1. declare @ObservableObject
class CreatureZoo : ObservableObject {
// โญ๏ธ 2. source of truth (@Published properties)
@Published var creatures = [
Creature(name: "Gorilla", emoji: "๐ฆ"),
Creature(name: "Peacock", emoji: "๐ฆ"),
]
}
๐ MyApp
@main
struct MyApp: App {
// โญ๏ธ 3. create data in app
@StateObject var data = CreatureZoo()
var body: some Scene {
SPCAssessableWindowGroup(app: self, assessmentCandidates: [CreatureZoo()]) {
NavigationView {
ContentView()
.navigationTitle("My Creatures")
}
// โญ๏ธ 4. put data in environment
.environmentObject(data)
}
}
}
๐ ContentView
struct ContentView: View {
// โญ๏ธ 5. inject data from environment
@EnvironmentObject var data : CreatureZoo
var body: some View {
SPCAssessableGroup(view: self) {
List {
Text("ContentView")
Section("Dance") {
NavigationLink("Make the Creatures Dance") {
DancingCreatures()
.navigationTitle("Dancing Creatures")
}
}
// โญ๏ธ 6. use data
ForEach(data.creatures) { creature in
// ...
}
}
}
}
}
StateObject ๆฏไธๅ Property Wrappers๏ผๅฎๅ งๅซ็่ณๆไธๅฎ่ฆ้ตๅพช ObservableObject ๅๅฎใ
@frozen @propertyWrapper
struct StateObject<ObjectType> where ObjectType : ObservableObject
SwiftUI โฉ
View โฉ State Modifiers โฉ
StateObject (struct)
ObservedObject (struct)
EnvironmentObject (struct)
Combine โฉ
ObservableObject (protocol)
wraps an object that conforms to ObservableObject.
Last updated