我正在制作一个ObservableObject
类,然后将其用于在所有应用程序中读取和写入值。当我在StateObject和ObservedObject中使用ObservableObject
时,它们不是相同的数据,但是它们在内存中创建了不同的变量,我们如何使StateObject
和ObservedObject
工作相同的数据?
例如,我的ObservableObject类有一个名为stringOfText
的变量,默认情况下有No Data!
,然后我制作了StateObject变量并开始读取默认值stringOfText
,然后更改了默认值值stringOfText,并且不会在我的ObservedObject
中显示更新!我在做什么错了?
class TextModel: ObservableObject {
@Published var stringOfText: String = "No Data!"
}
struct ContentView: View {
@ObservedObject var readStringOfTextView = TextModel()
var body: some View {
TextView()
Text(readStringOfTextView.stringOfText)
.foregroundColor(Color.black)
}
}
struct TextView: View {
@StateObject var textModel = TextModel()
var body: some View {
Text(textModel.stringOfText)
.padding()
.foregroundColor(Color.red)
Button(action: {
textModel.stringOfText = "Hello, world!"
}) {
Text("update string of Text")
.padding()
}
}
}
答案 0 :(得分:2)
如何使StateObject和ObservedObject处理同一数据?
您可以通过共享实例来实现它,例如:
class TextModel: ObservableObject {
static let shared = TextModel() // << here !!
@Published var stringOfText: String = "No Data!"
}
struct ContentView: View {
@ObservedObject var readStringOfTextView = TextModel.shared // << here !!
// ... other code
}
struct TextView: View {
@StateObject var textModel = TextModel.shared // << here !!
// ... other code
}
答案 1 :(得分:1)
您需要将TextModel
传递到子视图(在两个视图中使用相同实例):
struct ContentView: View {
@StateObject var readStringOfTextView = TextModel()
var body: some View {
TextView(textModel: readStringOfTextView) // pass here
Text(readStringOfTextView.stringOfText)
.foregroundColor(Color.black)
}
}
struct TextView: View {
@ObservedObject var textModel: TextModel // declare only
...
}