如何从导航堆栈弹出多个视图?

时间:2019-12-20 12:43:45

标签: swiftui react-navigation-stack

寻找一些指导,以一种简单的方法在SwiftUI中从导航堆栈弹出多个视图。 我使用NavigationLink将4个视图链接在一起。在最后一个视图中,我想跳回到初始的ContentView,将所有其他视图弹出堆栈。我不想使用每个视图的NavigationBar上的“后退”按钮来实现此目的。
提前致谢。 鲍勃 '''

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

'''

2 个答案:

答案 0 :(得分:1)

这并不是真正从堆栈中“弹出”视图,但是您的SceneDelegate可以将rootViewController设置为所需的任何视图(请参见默认SceneDelegate.swift的第28行)。就您而言,您希望它再次成为ContentView

例如,在您的SceneDelegate中添加以下内容:

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

然后在DView中,将NavigationLink更改为仅能执行以下操作的Button

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

答案 1 :(得分:1)

让Cenk Bilgen的答案更通用。

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

}

用法:

RootView.change(to: AnyView(DashboardView()))