Why doesn't Picker onTap and onChange work together?

75 views Asked by At

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)
1

There are 1 answers

2
JanMensch On

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:

Picker("", selection: question.answer) {
    ForEach(yesNoOptions, id: \.self) {
        Text($0)
            .tag($0) // <--- indicates which value this picker option relates to
    }
}

Depending on what data type you use for answer, you might need to also make it conform to Hashable, otherwise you will get a compiler error.