Using EnvironmentObject to share data between views

//
//  ContentView.swift
//  Test
//
//  Created by Toni Nichev on 1/3/24.
//

import SwiftUI


// Our observable object class
class GameSettings: ObservableObject {
    @Published var scoree = 0
    var test = 4
}

// A view that expects to find a GameSettings object
// in the environment, and shows its score.
struct ScoreView: View {
    // 2: We are not instantiating gameSetting here since it's already done in ContentView. 
    @EnvironmentObject var gameSettings: GameSettings
    
    var body: some View {
        Text("Score: \(gameSettings.scoree)")
        Text("Test: \(gameSettings.test)")
    }
}

struct ContentView: View {
    // 1: We instantiate GameSettings only here and pass it to the environmentObject at the end
    @StateObject var gameSettings = GameSettings()
    var body: some View {
        NavigationStack {
            VStack {
                Image(systemName: "globe")
                    .imageScale(.large)
                    .foregroundStyle(.tint)
                
                Button("Increase score") {
                    gameSettings.scoree += 1
                    gameSettings.test += 1
                }
                
                NavigationLink {
                    ScoreView()
                } label: {
                    Text("Show score")
                }
            }
        }
        .environmentObject(gameSettings)
    }
}

#Preview {
    ContentView()
}

#Preview {
    ScoreView().environmentObject(GameSettings())
}

 

Leave a Reply