For some reason DatePicker does not always update the date var associated with it. Am I doing something wrong? I can basically scroll around randomly and sometimes I can get to a point where my Text showing the current picked date (var $entryDate) differs from what the DatePicker shows that I have selected - my code:
struct addView: View {
@State private var entryDate: Date = Date()
var body: some View {
VStack {
HStack {
Spacer()
DatePicker("_", selection: $entryDate, in: ...Date(), displayedComponents: .date)
.labelsHidden()
.datePickerStyle(WheelDatePickerStyle())
.frame(minWidth: 0, maxWidth: .infinity, alignment: .center)
.environment(\.locale, Locale.current)
Spacer()
}
Text("\(entryDate)")
}
}
}
This is a known SwiftUI Bug. I solved it with a little workaround:
@State private var refresh = false
DatePicker("_" + (refresh ? "" : " "), selection: $entryDate, in: ...Date(), displayedComponents: .date)
.labelsHidden()
.datePickerStyle(WheelDatePickerStyle())
.frame(minWidth: 0, maxWidth: .infinity, alignment: .center)
.environment(\.locale, Locale.current)
And at the end of your View:
.onReceive(self.$refresh) { _ in
self.refresh.toggle()
}
Should even work with your labelsHidden().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With