How would you detect a change of value of a Datepicker while using SwiftUI and Combine? I need to invoke a method whenever the datepicker wheel is moved, to update a Text and a Slider.
I have looked for specific methods to identify the value change (using UIKit it was possible to associate an action to an event), but apparently I haven't found anything useful in the documentation (I've tried the onTapGesture methods, but that's not what I want, since it forces the user to tap the picker to update the other views, whereas I would like to have an automatic update whenever the user moves the wheel).
import SwiftUI
struct ContentView: View {
private var calendar = Calendar.current
@State private var date = Date()
@State private var weekOfYear = Double(Calendar.current.component(.weekOfYear, from: Date()) )
@State private var lastWeekOfThisYear = 53.0
@State private var weekDay: String = { () -> String in
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
let weekDay = dateFormatter.string(from: Date())
return weekDay
}()
var body: some View {
VStack {
// Date Picker
DatePicker(selection: $date, displayedComponents: .date, label:{ Text("Please enter a date") }
)
.labelsHidden()
.datePickerStyle(WheelDatePickerStyle())
.onTapGesture {
self.updateWeekAndDayFromDate()
}
// Week number and day
Text("Week \(Int(weekOfYear.rounded()))")
Text("\(weekDay)")
// Slider
Slider(value: $weekOfYear, in: 1...lastWeekOfThisYear, onEditingChanged: { _ in
self.updateDateFromWeek()
})
}
}
func updateWeekAndDayFromDate() {
// To do
}
func updateDateFromWeek() {
// To do
}
func setToday() {
// To do
}
func getWeekDay(_ date: Date) -> String {
//To do
}
}
I guess this could be solved using Combine (observableobject, published, sink, etc.), but I'm not experienced yet with Combine, therefore I'd like to ask for some help... any ideas? :)
Thanks a lot!