How it works
A DatePicker presents a control for selecting an absolute date, a time, or both, keeping a Date value in your model in sync with what the user chooses. Reach for it whenever a form needs a calendar or clock affordance — scheduling an event, setting a reminder, choosing a birthday — instead of asking the reader to type a date by hand. Because the picker reads and writes through a binding, the selected value flows directly into your state, and the visual presentation adapts to the style and the calendar components you ask it to display.
Bind the selection to a Date with the selection: parameter
DatePickeris driven by a two-wayBinding<Date>, so the control both shows the current value and writes the user's choice back to it. In the example the picker takesselection: $date, where$dateprojects a binding from the@State private var date = Date()declared above the body; any change in the wheel or calendar updates that property immediately.Label the control with the title argument
The first, unlabeled argument is the picker's title — the text that describes what the date is for and that some styles render alongside the control. Here it's the string
"Event Date", which uses the convenience initializer that turns a string literal into the label so you don't have to build a separateTextview.Choose what to edit with displayedComponents:
The
displayedComponents:parameter takes aDatePicker.Componentsoption set that decides whether the user edits the date, the time, or both. In the example it's set to[.date], so only the calendar portion is offered; passing[.hourAndMinute]or[.date, .hourAndMinute]would surface time editing as well.Pick a presentation with datePickerStyle(_:)
The
.datePickerStyle(_:)modifier swaps the picker's appearance without changing its behavior, ranging from a compact field to a full inline calendar. The example applies.graphical, which lays out a month grid for direct date selection; alternatives like.compactor.wheelproduce very different surfaces from the same binding.Lay it out like any view
Because
DatePickerconforms toView, it composes with ordinary layout modifiers and containers. In the example.padding()simply insets the graphical calendar from the edges — the modifier acts on the picker exactly as it would on any other SwiftUI view.
displayedComponents: [.date] to [.date, .hourAndMinute] to see the picker add a time control alongside the calendar.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct DatePickerDemo: View {
@State private var date = Date()
var body: some View {
DatePicker(
"Event Date",
selection: $date,
displayedComponents: [.date]
)
.datePickerStyle(.graphical)
.padding()
}
}