简体   繁体   English

在 SwiftUI 中创建具有特定日期的 DatePicker

[英]Create DatePicker with specific date in SwiftUI

Can I create a DatePicker that displays a specific date?我可以创建一个显示特定日期的DatePicker吗?

Here is my code:这是我的代码:

struct OnlineShop: View {
  @State private var date = Date()
  var body: some View {
    DatePicker(
      "Start Date",
      selection: $date,
      displayedComponents: [.date]
    )}
}

This code displays the current date on the picker.此代码在选择器上显示当前日期。 I want to show a specific date, such as 8/29/1987.我想显示一个特定的日期,例如 8/29/1987。

How can I do this?我怎样才能做到这一点?

Sure, just create your own date and set it.当然,只需创建您自己的日期并设置它。

struct OnlineShop: View {
    @State private var date = Date()
    
    var body: some View {
        Text("Hello, Online!")
        
        DatePicker(
            "Start Date",
            selection: $date,
            displayedComponents: [.date]
        )
        .onAppear {
            let calendar = Calendar(identifier: .gregorian)
            let components = DateComponents(year: 1987, month: 8, day: 29)
            if let customDate = calendar.date(from: components) {
                self.date = customDate /// set customDate to date
            }
        }
    }
}

Result:结果:

日期选择器显示“1987 年 8 月 29 日”

This is possible.这个有可能。 You can specify any component(s), like the year, month, day, hour, etc. using the DateComponents initializer with Calendar.current .您可以使用DateComponents初始值设定项和Calendar.current指定任何组件,例如年、月、日、小时等。

You need to initialize your date variable like so:您需要像这样初始化date变量:

@State private var date: Date = Calendar.current.date(from: DateComponents(year: 1987, month: 8, day: 27)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM