无法让 EnvironmentObject 更新 UI

时间:2021-07-12 17:26:11

标签: swift swiftui

我最初在我试图开发的项目的上下文中发布了另一个问题,但我什至无法让它在真空中工作,所以我想我会从基础开始。正如标题所暗示的,我的 EnvironmentObjects 并没有像他们应该的那样更新 UI;在以下代码中,用户在 ContentView 上输入文本,并且应该能够在下一个屏幕 SecondView 中看到该文本。

编辑:

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())
    }
}

但是,SecondView 不显示用户编写的文本,而是默认值 name(空白)。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

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())
    }
}