更改日期时,SwiftUI DatePicker 在中短日期格式之间跳转 [英] SwiftUI DatePicker jumps between short and medium date formats when changing the date

查看:28
本文介绍了更改日期时,SwiftUI DatePicker 在中短日期格式之间跳转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(使用 Xcode 12.3 和 iOS 14.3)

(Using Xcode 12.3 and iOS 14.3)

我使用具有默认样式 (DefaultDatePickerStyle) 的 DatePicker 组件来显示和编辑日期:该组件在标签中显示当前日期值并弹出一个点击该标签时的日历.到目前为止,一切都很好.

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.

当我更改日期时(以编程方式或在 UI 中手动更改),组件会不规律地更改其标签的日期格式.它似乎在 DateFormatter.Style.short.medium 值之间切换.请注意,日期格式不能以编程方式设置,它是 DatePicker 内部的.

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.

这是一个例子:

DatePicker 显示2021 年 2 月 7 日";我通过使用按钮减去一天来更改日期,使组件显示2/6/21";再次减去一天,显示变为2021 年 2 月 5 日".等等.有时它会为几个日期保持相同的格式,但大多数情况下它会在每次更改时切换.

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.

示例代码:

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()
    }
  }
}

省略 displayedComponentslabelsHidden 对问题没有影响.

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?

推荐答案

看起来像一个错误.这是一个找到的解决方法(使用 Xcode 13beta/iOS 15 测试)

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

这篇关于更改日期时,SwiftUI DatePicker 在中短日期格式之间跳转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆