在SwiftUI中使用EnvironmentObject时应用崩溃

时间:2019-06-22 20:16:50

标签: ios swift swiftui

EnviromentObject在多个视图之间不起作用。如果我在第二个视图上使用@EnviromentObject propertyWrapper,尽管我在ContentView().enviromentObject(SignUpManager())SceneDelegate中设置了PreviewProvider,它还是崩溃了。

这是我的代码:

struct ContentView : View {
    var body: some View {
        PresentationButton(destination: BackView()) {
            Text("click")
        }
    }
}

struct BackView : View {
    @EnvironmentObject var signupManager: SignUpManager

    var body: some View {
        VStack {
            Text("Here")
            TextField($signupManager.name, placeholder: Text(signupManager.name)).padding()
            PresentationButton(destination: BackView()) {
                Text("click")
            }
        }
    }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
        .environmentObject(SignUpManager())
    }
}
#endif

SceneDelegate中:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: ContentView().environmentObject(SignUpManager()))
        self.window = window
        window.makeKeyAndVisible()
    }
}

这是我的GitHub存储库:

https://github.com/SwiftiSwift/TestEnviromentObject

0 个答案:

没有答案