I am using SwiftUI DatePicker
in my app. I have created a selectedTime
state variable that is passed to the DatePicker
. I am also using a Text
component to display the selected time. As such, this text component gets updated whenever the time is changed. This works properly for all the cases, except when the user scrolls to 12 hours later, or earlier (e.g. if initial time is 3pm, and the user scrolls to 3am, or 5:10am to 5:10pm). Additionally, I am using an onChange
modifier to the time state variable, and call print(time)
inside the modifier. This also works whenever the user changes time, except for the above case of changing time by 12 hours. What could create this behaviour?
I am also enclosing a basic example of a SwiftUI view that does what I explained above:
import SwiftUI
struct TimePicker: View {
@State private var time = Date()
var body: some View {
VStack(alignment:.center, spacing:0) {
Spacer()
VStack {
Spacer()
HStack {
Spacer()
DatePicker("", selection: $time,
displayedComponents: .hourAndMinute)
.datePickerStyle(.wheel)
.fixedSize()
.accentColor(.red)
.onChange(of:time){ newVal in
print(newVal)
}
}
.datePickerStyle(WheelDatePickerStyle())
Spacer()
}
.background(.appBackground)
}
}
}