gpt4 book ai didi

swiftui - 如何从导航堆栈中弹出多个 View ?

转载 作者:行者123 更新时间:2023-12-03 13:44:30 28 4
gpt4 key购买 nike

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

'''

最佳答案

它并不是真正从堆栈中“弹出” View ,而是您的 SceneDelegate可以设置rootViewController到您想要的任何 View (参见默认 SceneDelegate.swift 的第 28 行)。在您的情况下,您希望它是 ContentView再次。

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

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

然后在 DView ,更改 NavigationLinkButton那就是:
(UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.toContentView()

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

关于swiftui - 如何从导航堆栈中弹出多个 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59425478/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com