Marwan Roushdy
Marwan Roushdy

Reputation: 1230

Modifying environment object for previews?

I am passing a view model to a view using environment objects. For the sake of previewing different states how can I change some properties in the environment object before passing it in the preview?

I'd like to do something like this but this doesnt work:

struct view_Previews: PreviewProvider {


    @EnvironmentObject static var authenticationViewModel: AuthenticationViewModel {
        get {
            let v = authenticationViewModel
            v.showResendCodeTimer = true
            return v
        }
    }

    static var previews: some View {

          SomeView().environmentObject(authenticationViewModel)
    }
}

Upvotes: 5

Views: 602

Answers (2)

ocodo
ocodo

Reputation: 30319

This approach works and is relatively simple.

struct view_Previews: PreviewProvider {
    static var previews: some View {
        let v = authenticationViewModel
        v.showResendCodeTimer = true    

        return SomeView().environmentObject(authenticationViewModel)
        // the return is the crucial part.
    }
}

Upvotes: 0

Asperi
Asperi

Reputation: 258591

Here is possible approach

static var previews: some View {
    Group {
        SomeView().environmentObject({ () -> AuthenticationViewModel in
                let v = AuthenticationViewModel()
                v.showResendCodeTimer = true
                return v
            }())
        SomeView().environmentObject({ () -> AuthenticationViewModel in
                let v = AuthenticationViewModel()
                v.showResendCodeTimer = false
                return v
            }())
    }
}

Upvotes: 4

Related Questions