nickcoding
nickcoding

Reputation: 475

Run code when date in DatePicker is changed in SwiftUI didSet function?

struct ViewName: View {
    @State private var selectedDay: Date = Date() {
        didSet {
            print("Old value was \(oldValue) and new date is \(self.selectedDay)")
        }
    }
    var body: some View {
        VStack {
            DatePicker(selection: $selectedDay, in: Date()..., displayedComponents: .date) { Text("") }
        }
    }
}

My question is, when I'm setting the selectedDate value in the DatePicker, why is there nothing printed to the console?

Upvotes: 1

Views: 451

Answers (1)

Asperi
Asperi

Reputation: 257859

My question is, when I'm setting the selectedDate value in the DatePicker, why is there nothing printed to the console?

For now didSet does not work for @State property wrapper.

Here is an approach to have side effect on DatePicker selection changed

struct ViewName: View {
    @State private var selectedDay = Date()

    var body: some View {
        let dateBinding = Binding(
            get: { self.selectedDay },
            set: {
                print("Old value was \(self.selectedDay) and new date is \($0)")
                self.selectedDay = $0
            }
        )
        return VStack {
            DatePicker(selection: dateBinding, in: Date()..., displayedComponents: .date) { Text("") }
        }
    }
}

Upvotes: 1

Related Questions