/

SwiftUI Forms: DatePicker

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
@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:

1
2
3
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:

DatePicker Example

When you tap on the date or time portion of the picker, it displays a dedicated picker interface:

Date Picker

Time Picker

Here’s the complete code for this example:

1
2
3
4
5
6
7
8
9
10
11
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:

1
2
3
DatePicker(selection: $dateChosen, in: ...Date(), displayedComponents: .date) {
Text("Pick a date and time")
}

Date Only

1
2
3
DatePicker(selection: $dateChosen, in: ...Date(), displayedComponents: .hourAndMinute) {
Text("Pick a date and time")
}

Time Only

Tags: SwiftUI, DatePicker, Forms, iOS, Swift