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存储库: