Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default date on DatePicker in SwiftUI?

Tags:

swiftui

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.

like image 453
Scott Joing Avatar asked Sep 15 '25 19:09

Scott Joing


1 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())
        }
    }
}
like image 102
cbjeukendrup Avatar answered Sep 17 '25 13:09

cbjeukendrup