Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

swiftui - How to pop multiple views off a navigation stack?

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

'''

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...