Search code examples
swiftuiswiftui-navigationlink

How to push to another view on DatePicker Selection changes on SwiftUI


I have a SwiftUI DatePicker and i need to push to another view on date selection.

I tried a NavigationLink on DatePicker and DatePicker.OnChange modifier but no luck.

any ideas?


Solution

  •    struct ContentView: View {
        @State var selectedDate = Date()
        @State var navigationActive = false
        var body: some View {
            NavigationView {
                VStack {
                    DatePicker("Select date", selection: $selectedDate)
                        .onChange(of: selectedDate, perform: { value in
                            print(selectedDate)
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { //this is because, otherwise user will not see the date selection on date picker
                                navigationActive = true
                            }
                            
                    })
                    NavigationLink("", destination: Text("Destination"), isActive: $navigationActive)
                }
            }
        }
    }