Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a left or right DragGesture() that trigger a switch case in SwiftUI?

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: ()
          }
    })
}
like image 293
Roland Lariotte Avatar asked Dec 13 '22 10:12

Roland Lariotte


1 Answers

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...

like image 100
user3069232 Avatar answered Mar 16 '23 00:03

user3069232