0

I have been struggling to implement a swipe-from-anywhere to go back gesture with the latest SwiftUI.

I found relevant posts like this: Swipe to go back only works on edge of screen?

But they utilize UIViewControllers, when my application uses just Views and the latest navigation stack API, being a view with a .navigationDestination call to handle going to the next view.

import SwiftUI

struct SwipeRightToPopModifier: ViewModifier {
    @Environment(\.presentationMode) var presentationMode
    @GestureState private var translation: CGFloat = 0

    func body(content: Content) -> some View {
        content
            .gesture(
                DragGesture()
                    .updating($translation) { value, state, _ in
                        state = value.translation.width
                    }
                    .onEnded { value in
                        let width = UIScreen.main.bounds.width
                        if value.translation.width > width * 0.5 {
                            self.presentationMode.wrappedValue.dismiss()
                        }
                    }
            )
    }
}


extension View {
    func swipeRightToPop() -> some View {
        modifier(SwipeRightToPopModifier())
    }
}

This is what I currently have. I can apply the swipeRightToPop function to any view, but it does not emulate the native functionality where it reveals the view behind it as you drag. I am unsure of where to go beyond this to make it emulate the built in left edge swipe.

0 Answers0