Search code examples
swiftnavigationview

How to set the initial view to have navigation bar back button SwiftUI


If I have two views HomeView() and ListView() normally I would have to click on the navigation link from the HomeView to go to the ListView, and inside the ListView() there would be a navigation bar back button which will allow me to go back to the HomeView. However if I set the startup view as ListView() neither the navigation view or the back button is there. So how can I set the initial view as ListView() but still containing the all the stuff from the navigation view?

struct HomeView: View{
    var body: some View {
        ZStack {
             NavigationView {
                  NavigationLink(destination: ListView()){}
             }
        }
    }
}
struct ListView: View{
    var body: some View {
        ZStack {
             List()...
        }
    }
}

Solution

  • struct HomeView: View{
        @State var isPresented = true
        var body: some View {
            ZStack {
                NavigationView {
                    NavigationLink(
                        destination: ListView(),
                        isActive: $isPresented,
                        label: {
                            Text("List View")
                        })
                }
            }
        }
    }
    struct ListView: View{
        var body: some View {
            ZStack {
                Text("List")
            }
        }
    }