I cannot get observable object model to work.
I have a simple demo of two views and a view model. The view model is;
import Foundation
class Score: ObservableObject {
@Published var total = 0
}
A button view to add one to the total;
struct ScoreButton: View {
@ObservedObject var score = Score()
var body: some View {
Button(action: {
score.total += 1
}, label: {
Text("Add 1 to Total")
})
}
}
Then a start view to show the results;
struct OBDemo: View {
@ObservedObject var result = Score()
var body: some View {
VStack {
ScoreButton()
.padding()
Text("Total = \(result.total)")
}
}
}
If I put the class, button and start view in one file it works
You're creating the two different instances of Score
:
struct ScoreButton: View {
@ObservedObject var result = Score() // instance #1
struct OBDemo: View {
@ObservedObject var result = Score() // instance #2
You need to use the same instance in both views - pass the @ObservedObject
to the child view:
struct OBDemo: View {
@ObservedObject var result = Score() // create in the parent view
var body: some View {
VStack {
ScoreButton(result: result) // <- pass to the child view
.padding()
Text("Total = \(result.total)")
}
}
}
struct ScoreButton: View {
@ObservedObject var score: Score // declare only
var body: some View {
Button(action: {
score.total += 1
}, label: {
Text("Add 1 to Total")
})
}
}