Home > AI > IOS > SwiftUI >

@EnvironmentObject

Example 1: Single View

UserSettings.swift

import Foundation
import SwiftUI


class UserSettings: ObservableObject {
    @Published var score: String = "0"
}

App.swift

import SwiftUI


@main
struct aaApp: App {
    var settings = UserSettings()
    
    var body: some Scene {
        WindowGroup {
            ContentView().environmentObject(settings)
        }
    }
}

ContentView.swift

struct ContentView: View {
    @EnvironmentObject var setting: UserSettings
    
    var body: some View {
        VStack {
            TextField("Input your score", text: $setting.score)
                .border(Color.black)
            Text("Score is \(setting.score)")
        }.padding()
    }
}

Example 2: Two Views

struct ContentView: View {
    @EnvironmentObject var setting: UserSettings
    
    var body: some View {
        NavigationView {
            VStack {
                Button ("Add Score") {
                    let a = Int(setting.score) ?? 0
                    setting.score = String(a + 1)
                }
                
                Text("\(setting.score)")
                
                NavigationLink(
                    destination: DetailView(),
                    label: {
                        Text("Navigate")
                    })
            }.padding()
        }
    }
}




struct DetailView: View {
    @EnvironmentObject var setting: UserSettings
    
    var body: some View {
        Text("\(setting.score)")
    }
}

Leave a Reply