@StateObject

╱🚧 under construction

SwiftUIviewstateobject ⟩ @StateObject

// ⭐️ 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

// ⭐️ 1. declare an observable object type
class CreatureZoo : ObservableObject {
    // ⭐️ 2. declare published properties
    @Published var creatures = [
        Creature(name: "Gorilla", emoji: "🦍"),
        Creature(name: "Peacock", emoji: "🦚"),
    ]
}

📁 MyApp

@main
struct MyApp: App {
    
    // ⭐️ 3. intialize an observable object
    @StateObject var data = CreatureZoo()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                // ⭐️ 4. put data in environment
                .environmentObject(data)
        }
    }
}

📁 ContentView

struct ContentView: View {
    
    // ⭐️ 5. inject data from environment
    @EnvironmentObject var data : CreatureZoo

    var body: some View {
        // ⭐️ 6. access data in subviews
    }
}

Last updated

Was this helpful?