The solution is don't use view model objects! You have to learn the View struct which is designed to hold your view data in a memory efficient hierarchy. It has a lot of magical features like dependency tracking and change detection which you just have to learn to use SwiftUI effectively.
@Observable is for model data it won't work for view data. You might get close to implementing the same behaviour as the View struct but you'll eventually get stuck so it is a complete waste of time.
Correct SwiftUI code would look like this:
struct ModalConfig {
var isPresented = false
var otherVar = ""
mutating func present() {
isPresented = true
otherVar = ""
}
mutating func dismiss() {
isPresented = false
}
}
struct ModalView: View {
@Binding var config: ModalConfig
var body: some View {
ZStack {
Color.yellow
.ignoresSafeArea()
Button("Close") {
config.dismiss()
}
}
}
}
struct ContentView: View {
@State var config = ModalConfig()
var body: some View {
Button("Present sheet modally") {
config.present()
}
.sheet(isPresented: $config.isPresented) {
ModalView(config: $config)
}
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: