7

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.")
        }
    }
}

'''

Bob
  • 159
  • 2
  • 8

2 Answers2

16

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.

Cenk Bilgen
  • 1,330
  • 9
  • 8
  • Thank you Cenk, that works! I would never have figured that out myself. I really appreciate the response. Many thanks, Bob. – Bob Dec 20 '19 at 14:45
  • Thanks - I have wasted hours looking for this, other solutions either crashed or meant injecting properties all the way through the navigation chain – user499846 Jul 27 '20 at 23:09
1

Making Cenk Bilgen's answer more generic.

struct RootView {
static func change(to view: AnyView) {
    guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
      let sceneDelegate = windowScene.delegate as? SceneDelegate else {
      return
    }
    let contentView = view
    sceneDelegate.window?.rootViewController = UIHostingController(rootView: contentView)
}

}

Usage:

RootView.change(to: AnyView(DashboardView()))
Parion
  • 428
  • 9
  • 18