【问题标题】:How to pop multiple views off a navigation stack?如何从导航堆栈中弹出多个视图?
【发布时间】:2020-04-12 23:32:26
【问题描述】:

寻找一些关于在 SwiftUI 中从导航堆栈中弹出多个视图的简单方法的指导。 我有 4 个使用 NavigationLink 链接在一起的视图。在最后一个视图中,我想跳回最初的 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.")
        }
    }
}

'''

【问题讨论】:

    标签: swiftui react-navigation-stack


    【解决方案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()))
    

    【讨论】:

      【解决方案2】:

      这并不是真正从堆栈中“弹出”视图,但您的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()
      

      如果您有多个场景,则需要更多。

      【讨论】:

      • 谢谢Cenk,这行得通!我自己永远也想不通。我非常感谢您的回复。非常感谢,鲍勃。
      • 谢谢 - 我已经浪费了几个小时来寻找这个,其他解决方案要么崩溃,要么意味着通过导航链一直注入属性
      猜你喜欢
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多