Trying to learn @EnvironmentObject in SwiftUi

I got this code from the SwiftUI by Example tutorial and it fails. The code compiles and runs ok but when any of the 2 button is tapped it crashes. The error I get is: Thread 1: Fatal error: No ObservableObject of type UserSettings found. A View.environmentObject(_:) for UserSettings may be missing as an ancestor of this view. and it is attached to line settings.score += 1

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

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

struct ContentView: View {
@EnvironmentObject var settings: UserSettings
var body: some View {
    NavigationView {
        VStack {
            Button("Increase Score") {
                settings.score += 1
            }
            NavigationLink(destination: DetailView()) {
                Text("Show Detail View")
            }
        }
    }
}}

Upvotes: 1

Views: 76

Answers (1)

swiftPunk
swiftPunk

Reputation: 1

EnvironmentObjects must be supplied by anscestor views!

Edit your main to this down code:

  @main
struct Your_ App_ Name_Here: App {  // <<: your app name!
    
    var body: some Scene {

        WindowGroup {

            ContentView()
                .environmentObject(UserSettings())

        }
 
    }
 
}

Upvotes: 1

Related Questions