How to restrict dates in DatePicker in SwiftUI?
pickers
In this post we will see how to allow only selection of dates in a certain time frame. Let’s consider an example where you only want to allow the user to select dates within the next 2 years from today for their trip.
The current selected date will be maintained by the @State
variable departureDate
.
The initializer of the DatePicker
accepts a range of dates. So we will need to pass this range where our startDate will be today’s date and the end date should be 2 years from now which we will call maxAllowedDate
.
Next, let’s calculate the maxAllowedDate
, which would be 2 years from today.
We can now initialize our DatePicker
with this range.
Now, the user will be only able to select dates in our specified range as shown above and all dates outside this range will get disabled for selection.