Reputation: 1230
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
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
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