1

我无法让可观察的对象模型工作。

我有两个视图和一个视图模型的简单演示。视图模型是;

import Foundation

class Score: ObservableObject {

    @Published var total = 0

}

一个按钮视图,可将总数加一;

struct ScoreButton: View {
    @ObservedObject var score = Score()

    var body: some View {
        Button(action: {
            score.total += 1
        }, label: {
            Text("Add 1 to Total")
        })
    }
}

然后是一个开始视图来显示结果;

struct OBDemo: View {

    @ObservedObject var result = Score()

    var body: some View {
        VStack {
            ScoreButton()
                .padding()
            Text("Total = \(result.total)")

        }
    }
}

如果我将类、按钮和开始视图放在一个文件中,它就可以工作

4

1 回答 1

0

您正在创建两个不同的实例Score

struct ScoreButton: View {
    @ObservedObject var result = Score() // instance #1
struct OBDemo: View {
    @ObservedObject var result = Score() // instance #2

您需要在两个视图中使用相同的实例 - 将 传递@ObservedObject给子视图:

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")
        })
    }
}
于 2020-09-01T21:25:34.677 回答