使用非今天的日期初始化日期选择器

Initializing the Date Picker with Date Other Than Today

我需要约会方面的帮助。如何使用存储的日期初始化 DatePicker?例如,假设用户输入了一个带有日期的条目。然后他确定日期是错误的并且想要更改日期。但目前此代码中的 DatePicker 将始终默认为今天的日期而不是存储的日期。

状态参数 startDate 不能用正文上方的存储日期初始化。看来我需要在正文中设置 startDate。

import SwiftUI
import Combine

struct GetDate: View {

    @ObservedObject var userData : UserData = UserData()
    @State private var startDate = Date()

    var body: some View {

        //let startDate = userData.startDate

        VStack (alignment: .leading) {

            Form {

                Text("startdate 1 = \(startDate)")


                // enter start date
                Section(header: Text("Enter Start Date")) {
                    HStack {
                        Image(systemName: "calendar.badge.clock")
                            .resizable()
                            .foregroundColor(Color(.systemRed))
                            .frame(width: 35, height: 35)

                        Spacer()

                        DatePicker("", selection: $startDate, in: ...Date(), displayedComponents: .date)
                            .datePickerStyle(CompactDatePickerStyle())
                    }
                }

                Button ( action: {
                    userData.saveDates(startDate: startDate)
                }) {

                    HStack {
                        Spacer()
                        Text("Save Dates?")
                        Spacer()
                    }
                }
            }
            .font(.body)
            .navigationBarTitle("Get Date", displayMode: .inline)
        }
    }
}


class UserData:  ObservableObject {

    @Published var startDate: Date = Date()  {
        didSet {
            UserDefaults.standard.set(startDate, forKey: "startDate")  // save
        }
    }


    init() {
        // save / retrieve trip dates
        if let sdate = UserDefaults.standard.object(forKey: "startDate") as? Date {
            startDate = sdate
            print("startDate 2 = \(startDate)")
        } else {
            UserDefaults.standard.set(Date(), forKey: "startDate")
        }
    }


    func saveDates(startDate: Date) -> () {

        self.startDate = startDate
        UserDefaults.standard.set(self.startDate, forKey: "startDate")

        print("startDate 3 = \(self.startDate)")
    }
}

使用@AppStorage 属性包装器:

struct GetDate: View {
  @AppStorage("startDate") var startDate = Date()
  @State private var selectedDate = Date()
  
  var body: some View {
    VStack (alignment: .leading) {
      Form {
        Text("startdate 1 = \(startDate)")
        Section(header: Text("Enter Start Date")) {
          HStack {
            Image(systemName: "calendar.badge.clock")
              .resizable()
              .foregroundColor(Color(.systemRed))
              .frame(width: 35, height: 35)
            Spacer()
            DatePicker("", selection: $selectedDate, in: ...Date(), displayedComponents: .date)
              .datePickerStyle(CompactDatePickerStyle())
          }
        }
        
        Button ( action: {
          startDate = selectedDate // save
        }) {
          HStack {
            Spacer()
            Text("Save Dates?")
            Spacer()
          }
        }
      }
      .font(.body)
      .navigationBarTitle("Get Date", displayMode: .inline)
    }
    .onAppear {
      selectedDate = startDate
    }
  }
}

// Support @AppStorage for `Date` type.
extension Date: RawRepresentable {
  private static let formatter = ISO8601DateFormatter()
  
  public var rawValue: String {
    Date.formatter.string(from: self)
  }
  
  public init?(rawValue: String) {
    self = Date.formatter.date(from: rawValue) ?? Date()
  }
}

只需在 .onAppear() 中将 startDate 重置为 userData.startDate

    .onAppear {
        startDate = userData.startDate
    }