WWDC21 SALE: Save 50% on all my Swift books and bundles! >>

SwiftUI Preview and @EnvironmentObject

Forums > SwiftUI

Hi all,

First post. Love the site & forum. I've googled away on this question but no sign of an answer anywhere

Is there any way to set the value of variables within an EnvironmentObject when generating a preview.

Toy example below. How do I generate a preview with myEnvObject.someBool = false.

This is easy to do if someBool is a local variable within the View's own struct but I don't see how I would do it when the variable belongs to an environment object.

Swift Class...

import Foundation

class SomeObject: NSObject, ObservableObject {
     @Published var someBool: Bool = true

     func someFunction() {
         someBool = false
     }
}

SwiftUI View...

import SwiftUI

struct ContentView: View {
    @EnvironmentObject var myEnvObject: SomeObject

    var body: some View {
        if myEnvObject.someBool == true {
            Text("This will show up in Preview")
        } else {
            Text("How do I generate a Preview showing this text?")
        }
    }
}

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

    }
}

Many thanks, Jim

   

Hi Jim

Add this in ContentView_Previews

struct ContentView_Previews: PreviewProvider {
    static let myEnvObject = SomeObject()

    static var previews: some View {
        ContentView()
            .environmentObject(myEnvObject)
    }
}

then it should work in preview. The Preview will only show the first bool eg true however if you want the 2nd text to show then change the if to false

   

Thanks so much @NigelGee

I am assuming from this that there is no "good" way to set a property of an environment object to a non-initial value in a preview. The only options seem to be temporarily editing either the View or the Environment Object (which then makes them incorrect) just to support previewing the view.

My real-world View has multiple branches, so this wouldn't work as a practical solution.

Thanks anyway

   

Save money with our WWDC sale!

SAVE 50% To celebrate WWDC21, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.