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
:
@State 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:
DatePicker(selection: $dateChosen, in: ...Date()) {
Text("Pick a date and time")
}
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:
struct ContentView: View {
@State private var dateChosen = Date()
var body: some View {
Form {
DatePicker(selection: $dateChosen, in: ...Date()) {
Text("Pick a date and time")
}
}
}
}
You can also choose to show only a specific element of the date, such as the date or time, by using the displayedComponents
parameter:
DatePicker(selection: $dateChosen, in: ...Date(), displayedComponents: .date) {
Text("Pick a date and time")
}
DatePicker(selection: $dateChosen, in: ...Date(), displayedComponents: .hourAndMinute) {
Text("Pick a date and time")
}
Tags: SwiftUI, DatePicker, Forms, iOS, Swift