1

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

1 Answer 1

0

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")
        })
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. How do I update the preview for ScoreButton? static var previews: some View { ScoreButton(score: #?#)
@Jmcg You can do ScoreButton(score: Score())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.