I have created a DragGesture in a View that should select a @State(Bool) whether the user swipe left or right.
The thing is that only swiping right is detected.
How to use .gesture() to capture whether a user is swiping left or right on his screen?
import SwiftUI
struct SwiftUIView: View {
  //MARK: Value to change on swipe gesture
  @State var swipeRight: Bool
  var body: some View {
    VStack {
      //MARK: Value displayed after user swiped
      Text($swipeRight ? "Right" : "Left")
    }
    .gesture(
      DragGesture()
        .onChanged { (value) in
          //MARK: What is it missing here?
          switch value.location.x {
          case ...(-0.5):
            self.swipeRight = false
            print("Swipe Left return false")
          case 0.5...:
            self.swipeRight = true
            print("Swipe Right return true")
          default: ()
          }
    })
}
                Swift 5, iOS 13
An improved version presented by [Mojtaba Hosseini ][1] here.
[1]: https://stackoverflow.com/users/5623035/mojtaba-hosseini. Place the enum and function before the body of ContentView.
enum SwipeHVDirection: String {
    case left, right, up, down, none
}
func detectDirection(value: DragGesture.Value) -> SwipeHVDirection {
if value.startLocation.x < value.location.x - 24 {
            return .left
          }
          if value.startLocation.x > value.location.x + 24 {
            return .right
          }
          if value.startLocation.y < value.location.y - 24 {
            return .down
          }
          if value.startLocation.y > value.location.y + 24 {
            return .up
          }
  return .none
  }
...
With it called inside a DragGesture. Calling it on onEnded to stop it firing multiple times.
.gesture(DragGesture()
        .onEnded { value in
        print("value ",value.translation.width)
          let direction = self.detectDirection(value: value)
          if direction == .left {
            // your code here
          }  
        }
      )
Obviously you need/can add other directions as needed...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With