How can I change the direction of the page transition animation?

89 Views Asked by At

When I tap on the navigation link on ContentView1 I want ContentView2 to slide in from the left rather than from the right.

So, I want to override the default.

I have not been able to find a solution which works with Swift 5.

The code I'm using is as follows:

import SwiftUI

struct ContentView1: View {

    var body: some View {
        NavigationView {
            NavigationLink(destination: ContentView2()) {
                Text("Hello, World!")
            }
            .navigationBarTitle("One")
        }
    }
}

struct ContentView2: View {

    var body: some View {
        Text("Hello, World #2!")
    }
}
2

There are 2 best solutions below

0
Gearóid Ó Ceallaigh On BEST ANSWER

Thank you everybody who took the time to answer.

It seems this behaviour isn't supported by default in swift 5.

I will need to rethink how I implement the screen.

0
Benzy Neez On

As mentioned in a comment, I don't think you can change the direction of the transition that the native navigation provides. Sliding in from the left is what you get when navigating back and that is the way Apple wants it to be.

However, there might be times when you want to launch an app with a nested context pre-loaded, in which case, navigating back would be a valid option. One way to do this is to use a NavigationStack with a path.

Here is how your example could be adapted to work this way:

enum NavDestination {
    case view1
    case view2
}

struct ContentView: View {

    @State private var navPath: [NavDestination] = [.view1]

    var body: some View {
        NavigationStack(path: $navPath) {
            ContentView2()
                .navigationDestination(for: NavDestination.self) { destination in
                    switch destination {
                    case .view1: ContentView1()
                    case .view2: ContentView2()
                    }
                }
                .navigationBarTitle("Two")
        }
    }
}

struct ContentView1: View {
    var body: some View {
        Text("Hello, World!")
            .font(.largeTitle)
            .bold()
    }
}

struct ContentView2: View {
    var body: some View {
        NavigationLink("Hello, World #2!", value: NavDestination.view1)
    }
}

Animation

Alternatively, you could abandon the native navigation and build your own context switcher, then you can use any transitions you like. It often works well to use a ZStack for this, as illustrated in the answer to How to animate a subview based on Picker-selection in SwiftUI?.