2

我是快速编程的新手。我试图通过专门通过类函数更改环境对象的值来使用环境对象来更新视图。我在 contentview 中有两个子视图,因为我希望在 UserData 环境对象中更改字符串时查看两个子视图是否一起更新。

但是,有一个错误提示“线程 1:致命错误:未找到 UserData 类型的 ObservableObject。可能缺少 UserData 的 View.environmentObject(_:) ...'

在 SceneDelagate.swift 中,我注入了环境对象:

let userData = UserData()

window.rootViewController = UIHostingController(rootView:contentView.environmentObject(userData))

用户数据.swift

final class UserData: ObservableObject {

    @Published var image: UIImage? = nil
    @Published var string  = "" 



}

StringGenerator.swift

class StringGenerator {

    @EnvironmentObject var userData: UserData


    func changeURL(){
        print("Changing string now from \(userData.string)")
        if self.userData.string == "HELLO"{
            self.userData.string = "BYE"

        }
        else{
            self.userData.string = "HELLO"
        }
        print("to \(userData.string)")
    }
}

SubView1.swift

struct SubView1: View {
    @EnvironmentObject var userData: UserData



    var body: some View {
        Text("\(userData.string)")

    }
}

SubView2.swift

struct SubView2: View {
    @EnvironmentObject var userData: UserData



    var body: some View {
        Text("\(userData.string)")

    }
}

内容视图.swift

struct ContentView: View {
    @EnvironmentObject var userData: UserData

    let stringGenerator = StringGenerator()

    var body: some View {

        VStack{

            Button(action: {
                print("Changing Text Now !")
                self.stringGenerator.changeURL()
                print("\(self.userData.string)")
            }) {
                Text("Change Text ")
            }


            SubView1()
            SubView2()


        }


    }
}

一般来说,我想知道如何通过类函数改变环境对象。

代码在我运行时崩溃。这里有什么问题?

4

1 回答 1

1

这是一个解决方案:

1) 在内容视图中

struct ContentView: View {
    @EnvironmentObject var userData: UserData

    let stringGenerator: StringGenerator   // declare-only

2) 在生成器中

class StringGenerator {

    var userData: UserData   // just member
    init(userData: UserData) {
      self.userData = userData
    }

3) 在场景委托中

let userData = UserData()

// inject generator via constructor with same user data
let contentView = ContentView(stringGenerator: 
                              StringGenerator(userData: userData))

window.rootViewController = UIHostingController(rootView: 
                              contentView.environmentObject(userData))
于 2020-05-29T10:44:10.443 回答