首页 > 解决方案 > 使用 .OnReceive 方法时无法更新 SwiftUI 预览

问题描述

我已经在 SwiftUI 视图中实现了 .OnReceive 方法,以便能够跟踪一些变量。

创建

状态

但正如您所看到的,我对所有 .onReceive 的代码进行了注释,原因是如果我不这样做,我会在画布上收到以下错误:

画布错误

这是我的 ContentView_Previews 结构: 在此处输入图像描述

谁能帮我理解错误?我怀疑 ContentView_Previews 结构需要一些额外的值才能解释画布上的视图。

谢谢您的帮助!

标签: iosswiftcanvasswiftuicombine

解决方案


此错误意味着预览无法呈现,其原因是它没有@EnvironmentObject var appState: StatesLoginView.onReceive.

所以,你需要设置它:

struct ContentView_Previews: PreviewProvider {
   static var previews: some View {
      LoginView()
         .previewLayout(.device)
         .environmentObject(States())  // here
   }
}

推荐阅读