Trouble getting EnvironmentObject to update the UI

Viewed 42

I originally posted another question asking this in the context of a project I was trying to develop, but I can't even get it to work in a vacuum so I figured I'd start with the basics. As the title suggests, my EnvironmentObjects don't update the UI as they should; in the following code, the user enters text on the ContentView and should be able to see that text in the next screen SecondView.

EDITED:

import SwiftUI

class NameClass: ObservableObject {
    @Published var name = ""
}
struct ContentView: View {
    @StateObject var myName = NameClass()
    
    var body: some View {
        NavigationView {
            VStack {
                TextField("Type", text: $myName.name)
                NavigationLink(destination: SecondView()) {
                    Text("View2")
                }
            }
        }.environmentObject(myName)
    }
}

struct SecondView: View {
    @EnvironmentObject var myself: NameClass
    var body: some View {
        Text("\(myself.name)")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(NameClass())
    }
}

However, the SecondView doesn't show the text that the user has written, but the default value of name (blank). What am I doing wrong here?

1 Answers
class NameClass: ObservableObject {
    @Published var name = ""
}

struct ContentView: View {
    @StateObject var myName = NameClass()
    
    var body: some View {
        NavigationView {
            VStack {
                TextField("Type", text: $myName.name)
                NavigationLink(destination: SecondView()) {
                    Text("View2")
                }
            }
        }.environmentObject(myName)
    }
}

struct SecondView: View {
    @EnvironmentObject var myself: NameClass
    var body: some View {
        Text("\(myself.name)")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(NameClass())
    }
}
Related