2

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)")
      }
  }
}

2 Answers 2

0

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().

1
  • using your suggestion results in: Cannot convert value of type '(_) -> ()' to expected argument type '(_.Output) -> Void'
    – Anro Swart
    Aug 5, 2020 at 9:07
0

Here's a workaround:

@State private var refresh: Bool = false

DatePicker("_"  + (refresh ? "" : " "), selection: $entryDate, displayedComponents: [.hourAndMinute])
                .datePickerStyle(.wheel)
                .labelsHidden()

Then whenever you edit $entryDate outside of the picker, call

self.refresh.toggle()

And the DatePicker will update properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.