I have SwiftUI views, which access the user defaults by using the property wrapper @AppStorage.
Now I would like to have a preview with multiple variations of the view depending on the same user default with different values. Is there a pure way to do that?
Currently I have a solution which is very probably a hack and supports only one variation of the user default. To do that I define the user settings in a sub views onAppear() method:
struct MyTestedView_Previews : PreviewProvider {
static var previews: some View {
VStack
{
VStack
{
MyTestedView
.previewLayout(.sizeThatFits)
}
.onAppear{
UserDefaults.standard.set(true, forKey: "myConsumedKey")
}
//VStack
//{
// MyTestedView
// .previewLayout(.sizeThatFits)
//}
//.onAppear{
// UserDefaults.standard.set(false, forKey: "myConsumedKey")
//}
}
}
}
When I have two VStack for different variations and I set the user defaults to different values in their onAppear(), only one user default value wins and I see one variation of my view twice.
What I also don't like on my solution, is that I don't know where this user default is stored. Is it stored temporary in the memory or do I even manipulate Xcode's user defaults?
Does anybody know if SwiftUI has already a solution to test different variations of user defaults in the preview?
Hey .. I'm using previews for different languages like this:
#Preview("English") {
ContentView()
.environment(\.locale, Locale(identifier: "EN"))
}
#Preview("Spanish") {
ContentView()
.environment(\.locale, Locale(identifier: "ES"))
}
It should work the same way for UserDefaults ;-)
Jackson