Home > Enterprise >  SwiftUI's new NavigationStack does not navigate to next screen
SwiftUI's new NavigationStack does not navigate to next screen

Time:11-08

I am trying to integrate NavigationStack in my SwiftUI app, I have three views CealUIApp, OnBoardingView and UserTypeView. I just want to navigate from OnBoardingView to UserTypeView when user presses a button in OnBoardingView

Below is my code for CealUIApp

@main
struct CealUIApp: App {
    
    @State private var path = [String]()
    
    var body: some Scene {
        WindowGroup {
            NavigationStack(path: $path){
                OnBoardingView(path: $path)
            }.navigationDestination(for: String.self) { string in
                UserTypeView()
                
            }
        }
    }
}

Now in OnBoardingView, the button code is as follows

Button {
                    path.append("UserTypeView")
                } label: {
                    Text("Hello")
                }

As soon as I press the button I am not navigated to UserTypeView, instead I just see a white screen with a warning icon at the centre

enter image description here

CodePudding user response:

I just want to navigate from OnBoardingView to UserTypeView when user presses a button in OnBoardingView, then try this approach, where .navigationDestination(...) is moved to the OnBoardingView, as shown in this example code:

@main
struct CealUIApp: App {
    
    @State var path = [String]()
    
    var body: some Scene {
        WindowGroup {
            NavigationStack(path: $path) {
                OnBoardingView(path: $path)
            }
        }
    }
}

struct OnBoardingView: View {
    @Binding var path: [String]
    
    var body: some View {
        Button {
            path.append("UserTypeView")
        } label: {
            Text("go to UserTypeView")
        }
        .navigationDestination(for: String.self) { string in
            UserTypeView()
        }
    }
}

struct UserTypeView: View {
    var body: some View {
        Text("UserTypeView")
    }
}
  • Related