Fabian H.
Fabian H.

Reputation: 688

Swift Preview problem with @EnvironmentObject

I am having trouble getting an updated preview when using @EnvironmentObject in my Swift project. In the simulator it works fine, but previewing is not. The error it shows is following:

ASET - Audio System Engineer Tools crashed due to missing environment of type: UserSettings. To resolve this add `.environmentObject(UserSettings(...))` to the appropriate preview.

However, when I try to add it, it keeps on coming with the same issue. Anyone have some helpful advise or solution?

Upvotes: 11

Views: 7577

Answers (2)

builderbob
builderbob

Reputation: 171

For those still having issues with the Preview but may not be related to this, you also have to inject it manually into the preview itself since it acts standalone and can't see your injection at the top level.

#Preview {
ContentView()
    .environmentObject(UserAuth())
}

Upvotes: 16

Fabian H.
Fabian H.

Reputation: 688

Found the answer which was already posted on stack overflow: instead of just putting it in the preview struct, I had to declare it like this, which makes the preview update without any issues:

struct CalculatorView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(UserSettings())
    }
}

Upvotes: 27

Related Questions