Arkyyn
Arkyyn

Reputation: 51

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. 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

import SwiftUI
import Combine

class ContentData: ObservableObject {
    @Published var text: String = "Yes"
}

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

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. I also tried a different version of the NewView.swift where I initialized the value with:

    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.

Upvotes: 0

Views: 1163

Answers (1)

sElanthiraiyan
sElanthiraiyan

Reputation: 6268

 @ObservedObject var contentData = ContentData()

ContentData() in the above line creates a new instance of the class ContentData.

You should pass the same instance from ContentView to NewView to retain the values. 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,

    struct NewView: View {

        @ObservedObject var contentData: ContentData

        ...
    }

Upvotes: 2

Related Questions