Home > Enterprise >  SwiftUI Push View with NavigationLink from modal view
SwiftUI Push View with NavigationLink from modal view

Time:09-28

I present a modal view with fullScreenCover by pressing "present my modal" button:

struct ContentView: View {

    @State var presentMyModal = false

    var body: some View {
        Text("Hello, world!")
            .fullScreenCover(isPresented: $presentMyModal) {
                    MyModalView()
            }
        Button(action: { presentMyModal = true },
               label: { Text("present my modal")})
    }
}

Then I want to push a new view with NavigationLink from this modal:

struct MyAlertView: View {

    @State var pushNavigationLinkedView = false

    var body: some View {
        Text("MyAlertView")
            .padding()
        Button(action: { pushNavigationLinkedView = true },
               label: { Text("push navigation linked view")})

        NavigationLink(destination: NavigationLinkedView(),
                       isActive: $pushNavigationLinkedView) {
            EmptyView()
        }
    }
}

And here is my NavigationLinkedView :

struct NavigationLinkedView: View {
    var body: some View {
        Text("NavigationLinkedView")
            .padding()
    }
}

But nothing happens when I press "push navigation linked view" button.

So is it allowed by apple guideline to push a view with NavigationLink from a modal view ? If yes, what is the best way to do it ?

Tested on iOS15 and XCode 13

CodePudding user response:

So is it allowed by apple guideline to push a view with NavigationLink from a modal view ?

Yes. Just make sure you have a NavigationView at the base of ‘MyAlertView’. The modal sheet creates a new view hierarchy, and NavigationLink only works when there’s a NavigationView somewhere in the hierarchy above.

  • Related