My view is called, but the default data is being used. My class is set like so
class UserWeatherData: ObservableObject {
@Published var currentDescription = "It's gonna rain!"
}
My view:
struct WeatherView: View {
@AppStorage("userTempChoice") var userTempChoice = "Fahrenheit"
@ObservedObject var weather = UserWeatherData()
var body: some View {
VStack {
Text("Tap Me")
.onTapGesture {
I set my data
}
}
}
}
Here is where things are not working for me and weather.currentDescription
is using the default data set above and not what I set.
struct SampleWeatherView: View {
@StateObject var weather = UserWeatherData()
var body: some View {
Text(weather.currentDescription)
}
}
To show the right usage of @StateObject
, the relationship of two views needs to be clarified.
But generally, if there are two initializers in your code, there may be two or more different instances of the same class, which causes unexpected behavior.
Assuming your SampleWeatherView
is a subview of WeatherView
in your view hierarchy, you can write something like this:
WeatherView
struct WeatherView: View {
@AppStorage("userTempChoice") var userTempChoice = "Fahrenheit"
//Use only 1 `@StateObject` where the only initializer exists
@StateObject var weather = UserWeatherData()
var body: some View {
VStack {
SampleWeatherView(weather: weather)
Text("Tap Me")
.onTapGesture {
//I set my data
//A simplified working example
weather.currentDescription = "Sunny all day!!!"
}
}
}
}
SampleWeatherView
struct SampleWeatherView: View {
//Do not put an initializer except `@StateObject`
@ObservedObject var weather: UserWeatherData
var body: some View {
Text(weather.currentDescription)
}
}
If you could show more context representing the view hierarchy of your app, there might be the right solution other than above code.