Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 !!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...