@StateObject
╱🚧 under construction
SwiftUI ⟩ view ⟩ state ⟩ object ⟩ @StateObject
Use @StateObject to declare and initialize a state object in a view that observes the object's data.
// ⭐️ 1. declare a type that conforms to `ObservableObject`
class Zoo : ObservableObject {
// ⭐️ 2. declare published value(s) in this type
@Published var creatures = [
Creature(name: "Gorilla", emoji: "🦍"),
Creature(name: "Peacock", emoji: "🦚"),
]
}
// content view
struct ContentView: View {
// ⭐️ 3. declare & initialize a state object
@StateObject var data = Zoo()
var body: some View {
// 4. access the state object's data in subviews
}
}📗 參考:Swift Playgrounds (Keep Going with Apps) - Sharing Data Between Views.
📁 CreatureZoo
📁 MyApp
📁 ContentView
SwiftUI ⟩
View ⟩ State Modifiers ⟩
StateObject (struct)
ObservedObject (struct)
EnvironmentObject (struct)
Combine ⟩
ObservableObject (protocol)
ObservableObject:declare an observable object type.
@Published:declare a published value in an observable object type.
@StateObject:initialize an observable object.
is property wrapper.
wraps an object that conforms to ObservableObject.
data model:the source of truth of your app.
Last updated
Was this helpful?