(Using Xcode 12.3 and iOS 14.3)
I use a DatePicker
component with the default style (DefaultDatePickerStyle
) to display and edit a date: the component shows the current date value in a label and pops up a calendar when tapping that label. So far, so good.
When I change the date (either programmatically or manually it in the UI), the component erratically changes the date format of its label. It seems to switch between the .short
and .medium
values of DateFormatter.Style
. Note that the date format cannot be set programmatically, it's internal to DatePicker
.
Here is an example:
The DatePicker
displays "Feb 7, 2021"; I alter the date by subtracting one day using a button, causing the component to display "2/6/21"; subtracting a day again, the display changes to "Feb 5, 2021" etc. Sometimes it keeps the same format for a few dates, but mostly it toggles on every change.
Example code:
struct DateView: View {
@State var date = Date()
var body: some View {
VStack(spacing: 20) {
Button("-1 day") {
date.addTimeInterval(-24*60*60)
}
Button("+1 day") {
date.addTimeInterval(24*60*60)
}
DatePicker(
"Date",
selection: $date,
displayedComponents: .date
).labelsHidden()
}
}
}
Omitting displayedComponents
or labelsHidden
has no effect on the issue.
The same issue can be observed when repeatedly opening the calendar popup and selecting dates: after closing the popup, the displayed date sometimes is in short format, and sometimes in medium format.
Any idea what's going on there?
An input element that is to be updated with the selected date from the datepicker. Use the altFormat option to change the format of the date within this field.
The size of the date picker can easily be changed manually. If you go over to Main. storyboard and simply click on the Date Picker, its size can easily be adjusted.
Refer to the following code example to set the format value of the DatePicker component. placeholder: 'Choose a date', format: 'dd-MMM-yyyy', });
Looks like a bug. Here is a found workaround (tested with Xcode 13beta / iOS 15)
DatePicker(
"Date",
selection: $date,
displayedComponents: .date
)
.labelsHidden()
.id(date) // << here !!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With