SwiftUI Forms: DatePicker
The DatePicker
control in SwiftUI allows us to create a date picker for selecting dates and times. Let’s take a closer look at how it works.
First, we need to create a property of type Date
and annotate it with @State
:
1 | private var dateChosen = Date() |
The @State
annotation is used so that we can modify this value from our DatePicker
view.
Next, we link this property to the DatePicker
view using the selection
parameter:
1 | DatePicker(selection: $dateChosen, in: ...Date()) { |
The selection
parameter is a binding to our dateChosen
property, and the in
parameter specifies the date range we want to allow. In the example above, we allow any date up to the current date.
Here’s how the DatePicker
looks in action:
When you tap on the date or time portion of the picker, it displays a dedicated picker interface:
Here’s the complete code for this example:
1 | struct ContentView: View { |
You can also choose to show only a specific element of the date, such as the date or time, by using the displayedComponents
parameter:
1 | DatePicker(selection: $dateChosen, in: ...Date(), displayedComponents: .date) { |
1 | DatePicker(selection: $dateChosen, in: ...Date(), displayedComponents: .hourAndMinute) { |
Tags: SwiftUI, DatePicker, Forms, iOS, Swift