I have a picker (segmented). I need onTap and onChange both on it. onTap works but onChange doesn't work. If I remove tap, just the onChange code works.
I need both because I am prefilling question.answer onAppear and hence onChange is triggered when prefilling. I need to know when user taps on segmented control.
Code is something like this:
Picker("", selection: question.answer) {
ForEach(yesNoOptions, id: \.self) {
Text($0)
}
}
.onTapGesture(perform: {
//do something
})
.onChange(of: question.answer.wrappedValue, perform: { newValue in
// do something
})
.pickerStyle(.segmented)
You need to assign a
tag
to each option in your segmented picker. Otherwise SwiftUI won't know what option in the picker corresponds to which value and then won't be able to update the selection value. To do that simply add the.tag(...)
modifier to your Text views in the picker like so:Depending on what data type you use for
answer
, you might need to also make it conform toHashable
, otherwise you will get a compiler error.