我不能让可观察到的对象模型工作。
我有一个两个视图的简单演示和一个视图模型。视图模型为;
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)")
}
}
}如果我将类、按钮和启动视图放在一个文件中,它就能工作。
发布于 2020-09-01 21:25:34
您正在创建两个不同的Score实例
struct ScoreButton: View {
@ObservedObject var result = Score() // instance #1struct 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")
})
}
}https://stackoverflow.com/questions/63695588
复制相似问题