11

I am trying to set the minimum date value of a date picker in SwiftUI using @Binding and @State.

I have three steppers, one for days, one for hours, and one for minutes. These are used to set the values of DateComponents.

What I want to see is the DatePicker adjust to the minimum date and time as I use the steppers. Is this possible?

I have edited this post and deleted all of the code examples because they were irrelevant to the solution. The problems were caused by deprecated DatePicker initializer code. See the answer below.

K. Law
  • 2,541
  • 3
  • 18
  • 27

1 Answers1

31

Here is the solution. Minimum and maximum dates were deprecated in SwiftUI DatePickers. The changes and solution were posted here: https://sarunw.com/posts/swiftui-changes-in-xcode-11-beta-4

If the link does not work, here are the examples.

DatePicker deprecated initializers Initializers with minimumDate and maximumDate are gone. Now we initialized it with ClosedRange, PartialRangeThrough, and PartialRangeFrom.

We use PartialRangeFrom for minimumDate.

DatePicker("Minimum Date",
    selection: $selectedDate,
    in: Date()...,
    displayedComponents: [.date])

We use PartialRangeThrough for maximumDate.

DatePicker("Maximum Date",
    selection: $selectedDate,
    in: ...Date(),
    displayedComponents: [.date])

If you want to enforce both minimumDate and maximumDate use ClosedRange

@State var selectedDate = Date()

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

DatePicker(
    selection: $selectedDate,
    in: dateClosedRange,
    displayedComponents: [.hourAndMinute, .date],
    label: { Text("Due Date") }
)

In all of the examples, the Date() can be replaced with a binding that is of type Date.

K. Law
  • 2,541
  • 3
  • 18
  • 27