swiftuiios-navigationview

How can I push a detailpage and remove all previous navigationlinks in swiftUI?


I have an app where there are multiple screens with textfields to create some new object. When the user selects "Create" on the last screen, an API call is performed which creates the new object.

From there I want to push the detail page of the newly created object, and (when the view is no longer visible) remove all the screens with textfields (as that is no longer relevant, and would only cause confusion. Luckily there is only one screen that should remain before the detailpage.

In UIKit, this would be performed by doing a push on the navigationController, and then editing the viewControllers array of the navigationController in the viewDidLoad of the new screen.

If I am correct, there is no way to edit the views in a SwiftUI NavigationView, so how can I perform this action in SwiftUI?


Solution

  • I solved it by adding an id to the NavigationView, and then setting this to another id in the viewmodel when it should reset.

    Like this:

    struct MyView: View {
        @StateObject var viewModel = ViewModel()
    
        var body: some View {
            NavigationView {
                // ...
            }
            .id(viewModel.id)
        }
    }
    

    In the viewmodel:

    class ViewModel: ObservableObject {
        @Published var id = UUID().uuidString
    
        func reset() {
            id = UUID().uuidString
        }
    }
    

    This resets the NavigationView as Swift thinks it's a different view because the id changed.