Search code examples
swiftswiftui

Any date range in DatePicker for SwiftUI


Normally we need a range, for example:

DatePicker(selection: $birthDate, in: ...Date(), displayedComponents: .date) 

We can select a date for previous date. How can we create a DatePicker which is able to select any date?

There is a method to allow to select a date within a specific range:

  var dateClosedRange: ClosedRange<Date> {
    let min = Calendar.current.date(byAdding: .day, value: -10000, to: Date())!
    let max = Calendar.current.date(byAdding: .day, value: 10000, to: Date())!
    return min...max
  }

Is there a better way?


Solution

  • Just leave the range out:

    DatePicker("Date of birth", selection: $birthDate, displayedComponents: .date)
    

    or:

    DatePicker(selection: $birthDate, displayedComponents: .date) { Text("Date of birth") }