Pop View from NavigationStack Animation Issue in SwiftUI

313 views Asked by At

I was wondering about the issue with the manual popping animation when changing the path in NavigationStack. When backing from Subview1 to RootView, a white screen appears in the background during the popping process (it should be yellow). However, the view pops up correctly when utilizing the 'back' button on the navigation bar.

I attached a screenshot. enter image description here

import SwiftUI

@Observable
class Router {
    static let shared = Router()
    var path : [String] = []
}

struct RootView: View {
    @Bindable var router = Router.shared
    
    var body: some View {
        NavigationStack(path: $router.path) {
            ZStack {
                Color.red.ignoresSafeArea()
                VStack {
                    Text("RootView")
                    Button {
                        router.path.append("SubView1")
                    } label: {
                        Text("push SubView1")
                    }
                }
            }
            .navigationDestination(for: String.self) { dest in
                SubView1(router: router)
            }
        }
    }
}

struct SubView1: View {
    var router : Router
    
    var body: some View {
        ZStack {
            Color.yellow.ignoresSafeArea()
            VStack {
                Text("RootView")
                Button {
                    router.path.removeLast()
                } label: {
                    Text("back to RootView")
                }
            }
        }
    }
}

#Preview {
    RootView()
}

1

There are 1 answers

0
Sweeper On

According to here, this seems to be a SwiftUI bug.

If you are just navigating back one view, you can use the dismiss environment value instead:

@Environment(\.dismiss) var dismiss

var body: some View {
    ZStack {
        Color.yellow.ignoresSafeArea()
        VStack {
            Text("RootView")
            Button {
                dismiss()
            } label: {
                Text("back to RootView")
            }
        }
    }
}