Search code examples
swiftuiswiftui-navigationviewswiftui-animation

Use dismiss() to pop view from NavigationStack with different animation


I am using the @Environment(.dismiss) private var dismiss and than dismiss() to pop current view from NavigationStack. In my app it should look like going forward however, rather than backwards.

When I use dismiss() the animation is sliding from left to right indicating going back. How can I change that to go from right to left, or any other animation for that matter?


Solution

  • Instead of using a NavigationLink you could utilize a switch-statement.

    struct ContentView: View {
        
        @State private var currentView: ShowView = .PARENT
        
        var body: some View {
            switch currentView {
            case .PARENT:
                NavigationStack {
                    Button("Show Subview") {
                        withAnimation {
                            currentView = .SUBVIEW
                        }
                    }
                }
                .transition(.backslide)
            case .SUBVIEW:
                NavigationStack {
                    Button("Show Parent") {
                        withAnimation {
                            currentView = .PARENT
                        }
                    }
                }
                .transition(.backslide)
            }
        }
    }
    

    For this example I used my own enum:

    enum ShowView {
        case PARENT, SUBVIEW
    }
    

    And for the backslide (which I guess is the transition you wanted):

    extension AnyTransition {
        static var backslide: AnyTransition {
            AnyTransition.asymmetric(
                insertion: .move(edge: .trailing),
                removal: .move(edge: .leading))}
    }
    

    The result looks like this (I added black background): To make it clear I added some black background

    Feel free to add more information if that is not what you wanted.