如何从导航堆栈中弹出多个视图? [英] How to pop multiple views off a navigation stack?

查看:26
本文介绍了如何从导航堆栈中弹出多个视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在寻找有关在 SwiftUI 中从导航堆栈中弹出多个视图的简单方法的一些指导.我有 4 个使用 NavigationLink 链接在一起的视图.在最后一个视图中,我想跳回初始 ContentView,从堆栈中弹出所有其他视图.我不想使用每个视图的 NavigationBar 上的返回"按钮来实现这一点.
提前致谢.鲍勃.'''

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

'''

推荐答案

这并不是真正从堆栈中弹出"视图,但是您的 SceneDelegate 可以设置 rootViewController到您想要的任何视图(请参阅默认 SceneDelegate.swift 的第 28 行).在您的情况下,您希望它再次成为 ContentView.

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.

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

For example in your SceneDelegate add something like:

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

然后在 DView 中,将 NavigationLink 更改为刚刚执行的 Button:

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.

这篇关于如何从导航堆栈中弹出多个视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆