Reputation: 588
I tired to build a multicomponent picker based on user3441734 solution for a dynamic picker. This picker lives in its own .swift file. I canβt figure out how to save the selection in a variable to access it from another view again.
Here is my code so far. I marked my wrong solution with an π and its error message below.
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])"
}
}
}
π Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols
Upvotes: 0
Views: 740
Reputation: 258345
It is not needed additional selection, because the selection is already stored in model, so
1) remove these lines
@State var selection: String = ""
// Save selection to variable π
selection = "\(self.model.manufacturerNames[model.selectedManufacturer])-\(self.model.stockNames[model.selectedStock])"
2) don't create inline model, just declare it to be able to inject via constructor
struct DynamicPicker: View {
@ObservedObject var model: Model // << here !!
3) use same model for DynamicPicker
that other dependent view, let's suppose it is called ManufacturerView
(having declared the same observed model as above). And there is some root view holding both, so it could be as
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 DynamicPicker
then ManufacturerView
will be updated automatically with corresponding selection, cause use same data source.
Upvotes: 0