Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pop multiple views off a navigation stack?

Looking for some guidance on a simple way to pop multiple views off a navigation stack in SwiftUI. I have 4 views chained together using NavigationLink. At the last view I would like to jump back to the initial ContentView, popping all the other views off the stack. I don't want to use the "Back" button on the NavigationBar of each view to achieve this.
Thanks in advance. Bob. '''

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: BView()) {
                    Text("This is View A, now go to View B.")
                }
            }
        }
    }
}
struct BView: View {
    var body: some View {
        NavigationLink(destination: CView()) {
                Text("This is View B, now go to View C.")
        }
    }
}

struct CView: View {
    var body: some View {
        NavigationLink(destination: DView()) {
                Text("This is View C, now go to View D.")
        }
    }
}
struct DView: View {
    var body: some View {
        // The following line adds ContentView onto the existing navigation stack. Instead, I want to pop the previous views off the stack, leaving me back at ContentView.
        NavigationLink(destination: ContentView()) {
            Text("This is View D, now jump back to View A.")
        }
    }
}

'''

like image 683
Bob Avatar asked Dec 20 '19 12:12

Bob


People also ask

How do I pop to a specific view in SwiftUI?

ContentView -> View1 -> View2 And from View2 you want to pop to the Root view.

How to dismiss a view in SwiftUI?

The first option is to tell the view to dismiss itself using its presentation mode environment key. Any view can read its presentation mode using @Environment(\. presentationMode) , and calling wrappedValue. dismiss() on that will cause the view to be dismissed.

What is navigation view SwiftUI?

NavigationView allows a hierarchical way of moving from one view to another. This includes going back to the previously navigated ones. It's an important component of SwiftUI since the majority of applications have multiple screens for presenting its functionality.


1 Answers

It's not really "popping" views off of the stack, but your SceneDelegate can set the rootViewController to any View you want (see line 28 of default SceneDelegate.swift). In your case you want it to be ContentView again.

For example in your SceneDelegate add something like:

func toContentView() {
    let contentView = ContentView()
    window?.rootViewController = UIHostingController(rootView: contentView)
  }

Then in DView, change the NavigationLink to a Button that just does:

(UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.toContentView()

If you have multiple scenes, you'll need a bit more.

like image 57
Cenk Bilgen Avatar answered Nov 04 '22 11:11

Cenk Bilgen