Set default date on DatePicker in SwiftUI?

Viewed 2816

I have this DatePicker inside a VStack, working fine:

VStack {
    DatePicker(selection: $birthDate, displayedComponents: .date) {
                Text("")
            }.padding(10)
            .labelsHidden()
            .datePickerStyle(WheelDatePickerStyle())
}

I'd like to be able to have the default date set to 40 years in the past so the user doesn't have to spin the year so far (most people aren't newborns). This can be done with DatePicker as shown in this SO answer. I don't know how to implement that in SwiftUI. Thanks for any help.

2 Answers

Why not just like this?

struct ContentView: View {
    @State private var birthDate: Date = Calendar.current.date(byAdding: DateComponents(year: -40), to: Date()) ?? Date()

    var body: some View {
        VStack {
            DatePicker(selection: $birthDate, displayedComponents: .date) {
                Text("")
            }
            .padding(10)
            .labelsHidden()
            .datePickerStyle(WheelDatePickerStyle())
        }
    }
}

You should initialise birthDate in the following way (tested & works with Xcode 11.2 / iOS 13.2)

@State private var birthDate: Date

init() {
    _birthDate = State<Date>(initialValue: Calendar.current.date(byAdding: 
                              DateComponents(year: -40), to: Date()) ?? Date())
}
Related