I would like to do something like this.
Code Block struct FirstView: View{ |
@State var selectedValue = 0 |
var selectedView : some View = SubviewA() |
var body: some View{ |
VStack{ |
Picker(selection: $selectedValue, label: Text("someText")){ |
Text("A").tag(0) |
Text("B").tag(1) |
Text("C").tag(2) |
Text("D").tag(3) |
Text("E").tag(4) |
Text("F").tag(5) |
}.pickerStyle(SegmentedPickerStyle()) |
selectedView |
} |
} |
} |
|
struct SubviewA: View{ |
var body: some View{ |
Text("Subview A") |
} |
} |
|
struct SubviewB: View{ |
var body: some View{ |
Text("Subview B") |
} |
} |
|
struct SubviewC: View{ |
var body: some View{ |
Text("Subview C") |
} |
} |
|
struct SubviewD: View{ |
var body: some View{ |
Text("Subview D") |
} |
} |
|
struct SubviewE: View{ |
var body: some View{ |
Text("Subview E") |
} |
} |
|
struct SubviewF: View{ |
var body: some View{ |
Text("Subview F") |
} |
} |
In the real scenario each subview is more complex than a simple Text. It has an image and a Picker, like this.
Code Block struct SubviewRealExample: View { |
|
@State var selection = [Int](repeatElement(0, count: 2)) |
|
var body: some View{ |
VStack{ |
ExercisePreview(background: "bgAcuity_thumb", symbol: ViewModel.getImageName()) |
MultiPicker(data: ViewModel.getData(), selection: $selection) |
} |
} |
} |
I would like selectedView to change every time the selected item in the picker changes. The only way that comes to my mind is the following.
Code Block struct FirstView: View{ |
@State var selectedValue = 0 |
var body: some View{ |
VStack{ |
Picker(selection: $selectedValue, label: Text("someText")){ |
Text("A").tag(0) |
Text("B").tag(1) |
Text("C").tag(2) |
Text("D").tag(3) |
Text("E").tag(4) |
Text("F").tag(5) |
}.pickerStyle(SegmentedPickerStyle()) |
if (selectedValue == 0){ |
SubviewA() |
}else if(selectedValue == 1){ |
SubviewB() |
}else if(selectedValue == 2){ |
SubviewC() |
}else if(selectedValue == 3){ |
SubviewD() |
}else if(selectedValue == 4){ |
SubviewE() |
}else if(selectedValue == 5){ |
SubviewE() |
}else{ |
EmptyView() |
} |
} |
} |
} |
|
struct SubviewA: View{ |
var body: some View{ |
Text("Subview A") |
} |
} |
|
struct SubviewB: View{ |
var body: some View{ |
Text("Subview B") |
} |
} |
|
struct SubviewC: View{ |
var body: some View{ |
Text("Subview C") |
} |
} |
|
struct SubviewD: View{ |
var body: some View{ |
Text("Subview D") |
} |
} |
|
struct SubviewE: View{ |
var body: some View{ |
Text("Subview E") |
} |
} |
|
struct SubviewF: View{ |
var body: some View{ |
Text("Subview F") |
} |
} |
If the subviews were only to be displayed I could use an Anyview array, but I need to access to the subviews state.