使用第二个视图中的数据初始化第二个视图中的类

时间:2020-02-22 23:44:33

标签: swiftui

在我最初的ContentView()中,我有一个呈现UIImagePicker的按钮,选择图像后,我导航到SecondView,可以在其中查看图像以及UIImagePickerController.InfoKey的数据

我目前有一个设置为EnviromentObject的ImageManager类,我将InfoKey传递给该类,然后设置该类中的所有变量-可以,但是感觉很混乱。

我想做的是当我导航到SecondView时初始化ImageManager类,因为那是唯一需要该数据的视图。

我尝试将InfoKey作为变量传递:

@State var InfoKey: [IImagePickerController.InfoKey: Any]

SecondView(key: self.infoKey)

但这会崩溃,因为在选择图片之前我没有任何数据

解决这个问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

@State必须具有初始值,因此只能使用空容器

@State var infoKey: [IImagePickerController.InfoKey: Any] = [:]

然后将其作为绑定传递给SecondView

SecondView(key: self.$infoKey)

其中

struct SecondView: View {
    @Binding var key: [IImagePickerController.InfoKey: Any]