- Property wrapper to observe other classes, and have them updated in view
- Update current view when something gets updated in other classses.
1. Set up
2. Create a custom class to hold extra data
3. @StateObject
Why is important?
- Whenever the view get updated and reloaded, @ObservedObject also gets reloaded. When user wants to reload the page but data should be remained, @StateObject is persist.
@StateObject var fruitViewModel: FruitViewModel = FruitViewModel()
→ @StateObject → INIT
→ @ObservedObejct → Subview
struct RandomScreen: View {
@Environment(\.dismiss) var dismiss
var body: some View {
ZStack{
Color.green.ignoresSafeArea()
Button(action: {
dismiss()
}, label: {
Text("GO BACK")
.foregroundStyle(.white)
.font(.largeTitle)
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
})
}
}
}
.toolbar(content: {
ToolbarItem(placement: .topBarTrailing) {
NavigationLink(destination: RandomScreen()) {
Image(systemName: "plus")
}
}
})
init(){
getFruits()
}
struct RandomScreen: View {
@Environment(\.dismiss) var dismiss
@ObservedObject var fruitViewModel: FruitViewModel
var body: some View {
ZStack{
VStack{
ForEach(fruitViewModel.fruitArray) { fruit in
Text(fruit.name)
.foregroundStyle(.white)
.font(.headline)
}
Spacer()
}
}
}
}
.toolbar(content: {
ToolbarItem(placement: .topBarTrailing) {
NavigationLink(
destination: RandomScreen(
fruitViewModel: FruitViewModel()
)) {
Image(systemName: "plus")
}
}
})
Today, I learned about ObservableObject
and StateObject. These are property
wrappers that observe other classes
and update them in the view.
Whenever the view is updated and
reloaded, @ObservedObject also gets
reloaded. If you want to reload the
page but keep the data intact,
@StateObject is preferred.
You can use the custom dataset
from current view or in another view.
This way, you can update the dataset
and preserve the data when transitioning
to a different view with their data set.
#visionOS #AppleVisionPro #VisionPro #SpatialApp #SwiftUI #AppDevelopment