[英]SwiftUI Using ObservableObject in View on New Sheet
I am struggling with figuring out how to use a value assigned to a variable in an ObservableObject class in another view on another sheet.我正在努力弄清楚如何在另一张纸的另一个视图中使用分配给 ObservableObject class 中变量的值。 I see that it gets updated, but when I access it in the new view on the new sheet it is reset to the initialized value.我看到它得到了更新,但是当我在新工作表上的新视图中访问它时,它被重置为初始化值。 How do I get it to retain the new value so I can use it in a new view on a new sheet?如何让它保留新值,以便我可以在新工作表上的新视图中使用它?
ContentData.swift内容数据.swift
import SwiftUI
import Combine
class ContentData: ObservableObject {
@Published var text: String = "Yes"
}
ContentView.swift ContentView.swift
import SwiftUI
struct ContentView: View {
@ObservedObject var contentData = ContentData()
@State private var inputText: String = ""
@State private var showNewView: Bool = false
var body: some View {
VStack {
TextField("Text", text: $inputText, onCommit: {
self.assignText()
})
Button(action: {
self.showNewView = true
}) {
Text("Go To New View")
}
.sheet(isPresented: $showNewView) {
NewView(contentData: ContentData())
}
}
}
func assignText() {
print(contentData.text)
contentData.text = inputText
print(contentData.text)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(contentData: ContentData())
}
}
NewView.swift NewView.swift
import SwiftUI
struct NewView: View {
@ObservedObject var contentData = ContentData()
var body: some View {
VStack {
Text(contentData.text)
}
}
}
struct NewView_Previews: PreviewProvider {
static var previews: some View {
NewView(contentData: ContentData())
}
}
I have tried many, many different methods I have seen from other examples.我尝试了很多很多从其他例子中看到的不同方法。 I tried doing it with @EnviromentObject but could not get that to work either.我尝试用@EnviromentObject 来做,但也无法让它工作。 I also tried a different version of the NewView.swift where I initialized the value with:我还尝试了不同版本的 NewView.swift,我在其中初始化了值:
init(contentData: ContentData) {
self.contentData = contentData
self._newText = State<String>(initialValue: contentData.text)
}
I think I am close, but I do not see what I am missing.我想我很接近,但我看不到我错过了什么。 Any help would be very much appreciated.任何帮助将不胜感激。 Thanks.谢谢。
@ObservedObject var contentData = ContentData()
ContentData()
in the above line creates a new instance of the class ContentData.上一行中的ContentData()
创建了 class ContentData 的新实例。
You should pass the same instance from ContentView to NewView to retain the values.您应该将相同的实例从 ContentView 传递给 NewView 以保留这些值。 Like,喜欢,
.sheet(isPresented: $showNewView) {
NewView(contentData: self.contentData)
}
Stop creating new instance of ContentData
in NewView
and add the ability to inject ContentData
from outside,停止在NewView
中创建ContentData
的新实例并添加从外部注入ContentData
的功能,
struct NewView: View {
@ObservedObject var contentData: ContentData
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.