0

我厌倦了为动态选择器构建基于user3441734 解决方案的多组件选择器。这个选择器存在于它自己的 .swift 文件中。我不知道如何将选择保存在变量中以再次从另一个视图访问它。

到目前为止,这是我的代码。我在下面用 an 及其错误消息标记了我的错误解决方案。

import SwiftUI
struct DynamicPicker: View {
    @ObservedObject var model = Model()

    // var to store the selection
    @State var selection: String = ""

    var body: some View {

        VStack {

            GeometryReader { geometry in

                HStack {

                    Picker(selection: self.$model.selectedManufacturer, label: Text("")){
                        ForEach(0 ..< self.model.manufacturerNames.count){ index in
                            Text(self.model.manufacturerNames[index])
                        }
                    }.labelsHidden()
                        .frame(maxWidth: geometry.size.width * CGFloat(0.3333))
                        .clipped()

                    Picker(selection: self.$model.selectedStock, label: Text("")){
                        ForEach(0 ..< self.model.stockNamesCount){ index in
                            Text(self.model.stockNames[index])
                        }
                    }
                    .id(self.model.id)
                    .labelsHidden()
                    .frame(maxWidth: geometry.size.width * CGFloat(0.6666))
                    .clipped()
                }
            }

            // Show selection
            Text("\(self.model.manufacturerNames[model.selectedManufacturer])-\(self.model.stockNames[model.selectedStock])")

            // Save selection to variable 
            selection = "\(self.model.manufacturerNames[model.selectedManufacturer])-\(self.model.stockNames[model.selectedStock])"
        }
    }
}

类型 '()' 不能符合 'View';只有结构/枚举/类类型可以符合协议

4

1 回答 1

0

不需要额外的选择,因为选择已经存储在模型中,所以

1)删除这些行

@State var selection: String = ""

// Save selection to variable 
selection = "\(self.model.manufacturerNames[model.selectedManufacturer])-\(self.model.stockNames[model.selectedStock])"

2)不要创建内联模型,只需声明它能够通过构造函数注入

struct DynamicPicker: View {
    @ObservedObject var model: Model  // << here !!

3)对DynamicPicker其他依赖视图使用相同的模型,假设它被调用ManufacturerView(声明了与上面相同的观察模型)。并且有一些根视图持有两者,所以它可能是

struct RootView: View {
    let model = Model() // << create it here

    var body: some View {
      VStack {
        DynamicPicker(model: self.model)
        ManufacturerView(model: self.model)
      }
    }
}

so when selection is updated in DynamicPickerthen ManufacturerViewwill be updated automatically with corresponding selection, cause use same data source.

于 2020-05-09T15:44:30.793 回答