How to change selected value of swiftUI DatePicker programmatically

Viewed 749

I have a swiftUI form consisting of three swiftUI pickers (two DatePickers and one standard string picker). I'm trying to change the selected value of the second DatePicker when the value of the string Picker changes.

I'm using .onChange on the string Picker to update the underlying values and this works fine (I added a Text row to display the due date value so the change can be verified). However, I would like the Due Date Picker to update the date it is displaying when the bound value changes.

*the values in the screen shot below are the initially set values.

enter image description here

struct FormWithPicker: View {
    @StateObject var formValues = FormValues()
    
    var body: some View {
        NavigationView {
            Form{
                // invoice date
                DatePicker("Invoice Date:", selection: $formValues.invoiceDate, displayedComponents: [.date])
                
                // terms
                Picker("Terms:", selection: $formValues.invoiceTerms) {
                    ForEach(formValues.terms, id: \.self) { term in
                        Text(term)
                    }
                }
                .onChange(of: formValues.invoiceTerms, perform: { _ in
                    formValues.incrementDueDate()
                })
                
                // due date
                DatePicker("Due Date:", selection: $formValues.dueDate, displayedComponents: [.date])
                    
                // text
                Text(formValues.dueDate.description)
                
            }
        }
    }
}
1 Answers

We need to make dependent DatePicker on externally changed dueDate and rebuild it. The .id modifier is good for this, like

DatePicker("Due Date:", selection: $formValues.dueDate, displayedComponents: [.date])
    .id(formValues.dueDate)    // << here !!

Tested with Xcode 13.2 / iOS 15.2

Related