我正在尝试使用DatePicker选择一天中的特定时间,然后选择该时间,将时间另存为ObservedObject并使用SwiftUI将其保存到我的UserDefaults中。我下面的代码的问题是,虽然在时间的初始设置之后保存了数据,但是如果时间发生了更改,则该更新不会像我期望的那样显示在我的DatePicker对象中。任何人都可以在这里查看我的代码在做什么我错了:
UserData.swift
import SwiftUI
class UserData: ObservableObject {
@Published var wakeUpTime: Date = UserDefaults.standard.object(forKey: "wakeUpTime") as? Date ?? Date() {
didSet {
UserDefaults.standard.set(self.wakeUpTime, forKey: "wakeUpTime")
}
}
}
AlarmSettingsView.swift
import SwiftUI
struct AlarmSettingsView: View {
static var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
return formatter
}()
@ObservedObject var userData = UserData()
var body: some View {
VStack {
Text("\(self.userData.wakeUpTime, formatter: AlarmSettingsView.self.dateFormatter)")
DatePicker("Please enter time.", selection: $userData.wakeUpTime, displayedComponents: .hourAndMinute)
.labelsHidden()
}
}
}