How it works
DatePickerComponents is an option set that tells a date picker which parts of a date and time it should let the user edit. By default a DatePicker exposes whatever components its style finds natural, but when you want a calendar without a clock, a clock without a calendar, or both together, you pass an explicit DatePickerComponents value through the picker's displayedComponents parameter. Reach for it whenever the precision of the value matters — scheduling a day-long event, picking only a time of day, or capturing a full timestamp.
Pass it through the displayedComponents parameter
The picker reads its component configuration from an initializer parameter typed as DatePickerComponents. In the example, the
DatePickeris created withdisplayedComponents: [.date, .hourAndMinute], which is the slot where the symbol plugs in and determines what the control draws.Choose the .date option for a calendar field
DatePickerComponents.date enables editing of the month, day, and year while hiding any time-of-day controls. Including
.datein the set, as the example does, gives the user a calendar-style field bound to themeetingvalue.Choose the .hourAndMinute option for a clock field
DatePickerComponents.hourAndMinute enables editing of the hour and minute and respects the locale's 12- or 24-hour convention. The example combines it with
.dateso the same picker edits both halves of the timestamp.Combine options with OptionSet array literal syntax
Because DatePickerComponents conforms to OptionSet, you build a value from an array literal and the picker shows the union of the listed members. The
[.date, .hourAndMinute]literal asks for both a calendar and a clock; passing a single-element set like[.date]restricts the control to one component.Let the Date binding carry the selected components
Whichever components you enable, the picker writes the user's edits back into the bound Date. Here
selection: $meetingties the editable fields to the@State private var meeting, so the value reflects exactly the components DatePickerComponents made available.
displayedComponents: [.date, .hourAndMinute] to [.hourAndMinute] and the picker drops its calendar field, leaving only a time-of-day control.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 DatePickerComponentsDemo: View {
@State private var meeting = Date()
var body: some View {
DatePicker(
"Meeting",
selection: $meeting,
displayedComponents: [.date, .hourAndMinute]
)
.padding()
}
}