Image generated with AI

Member-only story

Advanced DatePicker in SwiftUI

Nicola De Filippo
3 min readAug 20, 2024

How can we allow the user to select a date within a defined range? If you’re seeking an answer, read this post.

In this post, you’ll learn how to define different ranges:

  • From a start date to the end of time.
  • From the distant past to a defined endpoint.
  • Within a well-defined range.

Let’s get started.

From a start date to the end of time

struct ContentView: View {
var startDate = Date()
@State private var dateSelected = Date()
var body: some View {
VStack {
DatePicker(
"Select a date",
selection: $dateSelected,
in: startDate...,
displayedComponents: [.date])
.padding()
}
}
}

Therefore, we set the startDate to today, just to simplify things. In the DatePicker, we define the range with:

in: startDate...,

So, from today to end of the time.

From the distant past to a defined…

Nicola De Filippo
Nicola De Filippo

Written by Nicola De Filippo

Software Engineer and Entrepreneur

No responses yet

Write a response