How to pop multiple views off a navigation stack?

无人久伴 提交于 2020-08-25 05:18:10

问题


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

'''


回答1:


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.




回答2:


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()))


来源:https://stackoverflow.com/questions/59425478/how-to-pop-multiple-views-off-a-navigation-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!