Home > other >  How to call Navigation Link by pressing Button
How to call Navigation Link by pressing Button

Time:08-30

Using SwiftUI (Swift 5), I would like to press a button, which would navigate the app from one view to another. I have two buttons. I would like each button to navigate to a different view.

struct Test : View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: Text("First")) {
                    Text("Visible")
                }

                NavigationLink(destination: Text("Second")) {
                    Text("Invisible")
                }
                //EDIT: Also Invisible
                Text("Not rendered")

                Button(action: goToFirstPage){
                   Text("First Page")
                }

                Button(action: goToSecongPage){
                   Text("Second Page")
                }
            }
        }
    }
    private func goToFirstPage(){
        // need code for navigating to page here
    }

    private func goToSecondPage(){
        // need code for navigating to page here
    }

}

CodePudding user response:

After following recommendations from the comments in the OP, this is what I came up with.

struct ContentView: View {
    @State private var selection: String? = nil
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: PageA(), tag: "A", selection: $selection) { EmptyView() }
                NavigationLink(destination: PageB(), tag: "B", selection: $selection) { EmptyView() }

                                Button("Tap to show A") {
                                    selection = "A"
                                }

                                Button("Tap to show B") {
                                    selection = "B"
                                }
                            }
                            .navigationTitle("Navigation")

            }
        }
    }// end of body

  • Related