1

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")
            }
        }
    }
}}

1 Answer 1

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())

        }
 
    }
 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.