Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI DatePicker jumps between short and medium date formats when changing the date

Tags:

ios

swiftui

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

Date format changes when altering the date

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?

like image 365
dr_barto Avatar asked Feb 07 '21 16:02

dr_barto


People also ask

How do I change date format in DatePicker?

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.

How do I change the DatePicker size in Swiftui?

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.

How do I insert date format in DatePicker?

Refer to the following code example to set the format value of the DatePicker component. placeholder: 'Choose a date', format: 'dd-MMM-yyyy', });


1 Answers

Looks like a bug. Here is a found workaround (tested with Xcode 13beta / iOS 15)

demo

  DatePicker(
    "Date",
    selection: $date,
    displayedComponents: .date
  )
  .labelsHidden()
  .id(date)             // << here !!
like image 150
Asperi Avatar answered Oct 27 '22 18:10

Asperi