Search code examples
buttonswiftuinavigationlink

SwiftUI: How to Navigate from one view to another by clicking on a button


I am trying to move from one view to another, I have used NavigationLink as following:

        @State private var isActive = false


        NavigationLink(destination: DetailsView(),
                       isActive: $isActive) {
                        Text("")}
        Button(action: {
            print ("Clicked")
            self.isActive = true
        }){
            Text("More Details")
                .font(.headline)
                .bold()
                .padding(.all, 10)
                .padding(.leading, 10)
                .padding(.trailing, 10)
                .foregroundColor(.white)
                .background(Color.orange.frame(width: 300, height: 50) .clipShape(RoundedRectangle(cornerRadius: 20)))

        }

Unfortunately did not work!! The button did not take me to Details View!! I have already checked most of the solutions over here but nothing worked for me :( Please help!


Solution

  • To use a NavigationLink you have to wrap it in a NavigationView

    struct ContentView: View {
        var body: some View {
            NavigationView {   // <--- add this
                NavigationLink(destination: DetailsView()) {
                    Text("ADD TO CART")
                        .font(.headline)
                        .bold()
                        .padding(.all, 10)
                        .padding(.leading, 10)
                        .padding(.trailing, 10)
                        .foregroundColor(.white)
                        .background(Color.orange.frame(width: 300, height: 50) .clipShape(RoundedRectangle(cornerRadius: 20)))
    
                }
            }
        }
    }