SwiftUI .gestureモディファイア(modifier)でスワイプ(swipe)の種類判断
DragGestureの位置情報から角度を計算、スワイプ(swipe)の種類を判断する。
計算と角度範囲は図を参照。
スワイプ(swipe)の種類
up:下から上
down:上から下
left:右から左
right:左から右
各方向60度範囲としたサンプルソース
: ExampleView() .gesture(DragGesture(coordinateSpace: .global) .onEnded({ value in let swipeType = self.swipeType(startLocation: value.startLocation, location: value.location) print("SwipeType:\(swipeType)") }) ) :
func swipeType(startLocation: CGPoint, location: CGPoint) -> SwipeType { var swipeType: SwipeType = .none print("startLocation:\(startLocation)") print("location :\(location)") let b = startLocation.y - location.y let c = location.x - startLocation.x let degree = atan2(b, c) * 180 / Double.pi print("\(#function) b:\(b)") print("\(#function) c:\(c)") print("\(#function) :\(degree)") if -30.0 <= degree && degree <= 30 { swipeType = .right } else if 60.0 <= degree && degree <= 120 { swipeType = .up } else if (150.0 <= degree && degree <= 180.0) || (-180 <= degree && degree <= -150.0) { swipeType = .left } else if -120.0 <= degree && degree <= -60.0 { swipeType = .down } return swipeType } enum SwipeType: Int { case none case up case down case left case right }