3

in the process of programming my first iOS app I encountered a new issue that I was not able to find a solution for so far: I want to use an environment object to pass information to various views.

I know there are many explanations and tutorials for this (e.g. here on hackingwithswift.com: https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views

However, the entirety of these tutorials seems to be using "scene delegate" which is not existent in Xcode 12 as per my current understanding.

Therefore I am struggling on how/where to place to place an environment object in my apps environment and how to connect it to my content view/other views.

Where to place this code snippet? Does it go into content view?

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

Would anyone be able to help on this one? I would appreciate it :)

Malburrito
  • 860
  • 7
  • 23

1 Answers1

5

You can create and inject it in scene of window group, like

@main
struct MyApp: App {
    @StateObject var userSettings = UserSettings()

    var body: some Scene {
        WindowGroup {
           ContentView().environmentObject(userSettings)
        }
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690