I have a picker with certain list of items (say- Add, Edit, Delete) and on selection on particular item, I need to move to a different screen. I tried onTapGuesture() but control does not go inside when I debug the same.
Asked
Active
Viewed 1,892 times
1 Answers
3
I found 3 different ways to achieve this. The last one I took here. So, there are all these ways, you can choose which you want:
struct PickerOnChange: View {
private var options = ["add", "edit", "delete"]
@State private var selectedOption = 0
@State private var choosed = 0
var body: some View {
VStack {
Picker(selection: $selectedOption.onChange(changeViewWithThirdWay), label: Text("Choose action")) {
ForEach(0 ..< self.options.count) {
Text(self.options[$0]).tag($0)
}
}.pickerStyle(SegmentedPickerStyle())
// MARK: first way
VStack {
if selectedOption == 0 {
Text("add (first way)")
} else if selectedOption == 1 {
Text("edit (first way)")
} else {
Text("delete (first way)")
}
Divider()
// MARK: second way
ZStack {
AddView()
.opacity(selectedOption == 0 ? 1 : 0)
EditView()
.opacity(selectedOption == 1 ? 1 : 0)
DeleteView()
.opacity(selectedOption == 2 ? 1 : 0)
}
Divider()
// MARK: showing third way
Text("just to show, how to use third way: \(self.choosed)")
Spacer()
}
}
}
func changeViewWithThirdWay(_ newValue: Int) {
print("will change something in third way with: \(choosed), you can do everything in this function")
withAnimation {
choosed = newValue
}
}
}
// MARK: the third way
extension Binding {
func onChange(_ handler: @escaping (Value) -> Void) -> Binding<Value> {
return Binding(
get: { self.wrappedValue },
set: { selection in
self.wrappedValue = selection
handler(selection)
})
}
}
You'll achieve this with code snippet:

Hrabovskyi Oleksandr
- 3,070
- 2
- 17
- 36
-
var options = ["General", "About"] @State private var selectedOption = 0 If I need to read data from model class and set default selected item, should I be using @Binding? – Mar 13 '20 at 05:14
-
-
Should I be using @ObservedObject if my array of options are coming from model class? Also, how to set the default state in this case ? – Mar 13 '20 at 10:58
-
I get error - > Cannot use instance member 'ModelClass' within property initializer; property initializers run before 'self' is available , if I try to set @State var selected = ModelClass.options[0] – Mar 13 '20 at 11:07
-
@RamyaSharma I think better to make another question with your code snippet and error message. It's not quite clear for me now, what you want to achieve and how you want to work with your data – Hrabovskyi Oleksandr Mar 13 '20 at 14:29
-
https://stackoverflow.com/questions/60681453/how-to-populate-picker-from-viewmodel-object-setting-to-initial-state-of-first – Mar 14 '20 at 09:44
-
@RamyaSharma I answered - added the working solution. But read **P.S.**, you could be downvoted because of quality of question – Hrabovskyi Oleksandr Mar 14 '20 at 14:54