Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set SwiftUI DatePicker minimumDate using bindings?

Tags:

swiftui

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.

like image 216
K. Law Avatar asked Jan 22 '26 04:01

K. Law


2 Answers

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.

like image 133
K. Law Avatar answered Jan 23 '26 20:01

K. Law


For disabling future dates

DatePicker("Select a Date",
                   selection: $selectedDate,
                   in: Date.distantPast...maxDate,
                   displayedComponents: [.date])

or

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

and for disabling past dates

DatePicker("Select a Date",
                   selection: $selectedDate,
                   in: minDate...Date.distantFuture,
                   displayedComponents: [.date])

or

DatePicker("Select a Date",
                       selection: $selectedDate,
                       in: minDate...,
                       displayedComponents: [.date])
like image 36
Amal T S Avatar answered Jan 23 '26 19:01

Amal T S