我无法使用可观察的对象模型。
我有两个视图和一个视图模型的简单演示。视图模型是;
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)")
}
}
}
如果我将类,按钮和开始视图放在一个文件中,它将起作用
答案 0 :(得分: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")
})
}
}