Disable future date selection for DatePicker in SwiftUI

Previously I have already discussed about the DatePicker control and show you how easy SwiftUI makes it for us to create a date picker using this. Today, you are going to learn how to disable future date selection in SwiftUI DatePicker.

From my personal experience, it is a common need to disable the selection of upcoming or future dates. So sometimes it becomes necessary not to allow users to select dates from the future.

Below is given an example of DatePicker where you can see how to perform this:

    @State private var dateOfBirth = Date.now
    var body: some View {
        DatePicker("Date:", selection: $dateOfBirth, in: ...Date(), displayedComponents: .date)

Now when the user taps on the date picker for selecting a date, the user will see:

Date picker calander

Today is 3rd March at the time of writing this tutorial. You can see all the date after March 3 is not available to select. This is because all those are future dates and here future date selection is not allowed.

So what we did do with our DatePicker?

We have provided the in: ...Date() in our DatePicker that is doing the job we want:

            selection: $dateOfBirth,
            in: ...Date(), // Disable selecting future dates
            displayedComponents: .date