Search code examples
swiftswiftui

How to set an Environment Object in preview


My view needs an environment object which is set in the SceneDelegate by adding it to the window.rootViewController. How can I set an environment object to be used for the preview?


Solution

  • You add it using .environmentObject(_:) modifier:

    struct ContentView_Previews: PreviewProvider {
    
        static var previews: some View {
            ContentView()
                .environmentObject(YourObject())
        }
    }