Multi window SwiftUI app using shared and not-shared model
1 min readApr 9, 2021
ObservedObject
The @ObservedObject
does not bind the ObservableObject
to the view where it is defined. That means that when we change a value in one view, it is going to be propagated between the views as well.
Here is the code to make views with the shared state.
import SwiftUIpublic class ContentViewModel: ObservableObject {
@Published var value: String = ""
}struct ContentView: View {
@ObservedObject var viewModel: ContentViewModel = ContentViewModel()
var body: some View {
TextField("Value", text: $viewModel.value)
.padding()
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
}
StateObject
The @StateObject
is binded to a view. That means that each opened view gets its own state.
Here is the code to make views with its own independent values.
import SwiftUIpublic class ContentViewModel: ObservableObject {
@Published var value: String = ""
}struct ContentView: View {
@StateObject var viewModel: ContentViewModel = ContentViewModel()
var body: some View {
TextField("Value", text: $viewModel.value)
.padding()
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
}
You can watch this 30 minutes video with the explanation of the difference between
@ObservedObject
and@StateObject