SwiftUI ObservedObject 不跨视图更新
SwiftUI ObservedObject not updating across views
我无法使用可观察对象模型。
我有两个视图和一个视图模型的简单演示。视图模型是;
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)")
}
}
}
如果我将 class、按钮和开始视图放在一个文件中,它就可以工作
您正在创建 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")
})
}
}
我无法使用可观察对象模型。
我有两个视图和一个视图模型的简单演示。视图模型是;
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)")
}
}
}
如果我将 class、按钮和开始视图放在一个文件中,它就可以工作
您正在创建 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")
})
}
}