Scott Joing
Scott Joing

Reputation: 82

Set default date on DatePicker in 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.

Upvotes: 4

Views: 4962

Answers (2)

cbjeukendrup
cbjeukendrup

Reputation: 3446

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())
        }
    }
}

Upvotes: 4

Asperi
Asperi

Reputation: 258385

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())
}

Upvotes: 2

Related Questions