swiftuiswipeapple-watch

How to detect Swiping UP, DOWN, LEFT and RIGHT with SwiftUI on a View


I'm getting into building Apple Watch apps.

What I'm currently working on will require me to make use of detecting swipes in the four main directions (UP, DOWN, LEFT and RIGHT)

The problem is I have no idea how to detect this. I've been looking around and I'm reaching dead ends.

What can I do to my view below to just print swiped up when the user swipes UP on the view?

struct MyView: View {
    var body: some View {
        Text("Hello, World!")
    }
}

Thanks.


Solution

  • Based on Benjamin's answer this is a swiftier way to handle the cases

    .gesture(DragGesture(minimumDistance: 3.0, coordinateSpace: .local)
        .onEnded { value in
            print(value.translation)
            switch(value.translation.width, value.translation.height) {
                case (...0, -30...30):  print("left swipe")
                case (0..., -30...30):  print("right swipe")
                case (-100...100, ...0):  print("up swipe")
                case (-100...100, 0...):  print("down swipe")
                default:  print("no clue")
            }
        }
    )