【问题标题】:Set default date on DatePicker in SwiftUI?在 SwiftUI 中的 DatePicker 上设置默认日期?
【发布时间】:2020-03-02 17:53:22
【问题描述】:

我在 VStack 中有这个 DatePicker,工作正常:

VStack {
    DatePicker(selection: $birthDate, displayedComponents: .date) {
                Text("")
            }.padding(10)
            .labelsHidden()
            .datePickerStyle(WheelDatePickerStyle())
}

我希望能够将默认日期设置为过去 40 年,这样用户就不必旋转到目前为止的年份(大多数人不是新生儿)。这可以使用 DatePicker 完成,如 this SO answer 所示。我不知道如何在 SwiftUI 中实现它。感谢您的帮助。

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    为什么不这样呢?

    struct ContentView: View {
        @State private var birthDate: Date = Calendar.current.date(byAdding: DateComponents(year: -40), to: Date()) ?? Date()
    
        var body: some View {
            VStack {
                DatePicker(selection: $birthDate, displayedComponents: .date) {
                    Text("")
                }
                .padding(10)
                .labelsHidden()
                .datePickerStyle(WheelDatePickerStyle())
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您应该按以下方式初始化birthDate(经过测试并适用于 Xcode 11.2 / iOS 13.2)

      @State private var birthDate: Date
      
      init() {
          _birthDate = State<Date>(initialValue: Calendar.current.date(byAdding: 
                                    DateComponents(year: -40), to: Date()) ?? Date())
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多