【问题标题】:Init a class from my second view with data from the first从我的第二个视图使用第一个视图中的数据初始化一个类
【发布时间】:2020-02-23 11:55:46
【问题描述】:

In my initial ContentView() I have a button that presents a UIImagePicker, when an image is chosen I then navigate to SecondView where I can view the image and it’s data from UIImagePickerController.InfoKey

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

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

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

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

SecondView(key: self.infoKey)

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

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

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    @State 必须有初始值,所以只使用空容器

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

    然后将其作为绑定传入SecondView

    SecondView(key: self.$infoKey)
    

    在哪里

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

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多