How to make simple swipe vertically to dismiss in SwiftUI

Issue #813

Use simultaneousGesture to not collide with potential horizontal scrolling in carousel view, and check that we’ more accidentally swipe horizontally.

import SwiftUI

struct SwipeToDismissModifier: ViewModifier {
    var onDismiss: () -> Void
    @State private var offset: CGSize = .zero

    func body(content: Content) -> some View {
        content
            .offset(y: offset.height)
            .animation(.interactiveSpring(), value: offset)
            .simultaneousGesture(
                DragGesture()
                    .onChanged { gesture in
                        if gesture.translation.width < 50 {
                            offset = gesture.translation
                        }
                    }
                    .onEnded { _ in
                        if abs(offset.height) > 100 {
                            onDismiss()
                        } else {
                            offset = .zero
                        }
                    }
            )
    }
}

We can also combine gesture to exclude or sequence with other DragGesture to achieve desired effect

Read more

Written by

I’m open source contributor, writer, speaker and product maker.

Start the conversation