2
4

More than 3 years have passed since last update.

UIPanGestureRecognizer(パン)とUISwipeGestureRecognizer(スワイプ)をいっしょに使う

Last updated at Posted at 2020-11-17

同じviewにパンとスワイプを同時に与えると、パンしか効かなくなる。
素早くスワイプした時だけスワイプを発火してそれ以外の時はパンするコードがこちら。
基本PanGestureで、Pan速度が一定を超えた時だけSwipeになります。
スタックオーバーフローの記事の引用です。元記事には実際のジェスチャアニメーションの様子があります。

let swipeVelocity: CGFloat = 500

@objc func didPan(_ sender: Any) {

guard let panGesture = sender as? UIPanGestureRecognizer else { return }

let gestureEnded = Bool(panGesture.state == UIGestureRecognizer.State.ended)
let velocity = panGesture.velocity(in: self.view)

if gestureEnded && abs(velocity.y) > swipeVelocity {
        handlePanAsSwipe(withVelocity: velocity.y)
    } else {
        handlePan(panGesture)
    }
}

func handlePan(_ recognizer: UIPanGestureRecognizer) {
    switch recognizer.state {
    // Panの操作を書く
    case .began:
    case .changed:
    default: break
    }
}

func handlePanAsSwipe(withVelocity velocity: CGFloat) {
    if velocity > 0 {
        print("down")
        // 下Swipeの操作を書く
    } else {
        print("up")
        // 上Swipeの操作を書く
    }
}
let panOrSwipe = UIPanGestureRecognizer(target: self, action: #selector(didPan(_:)))
view.addGestureRecognizer(panOrSwipe)

🐣


お仕事のご相談こちらまで
rockyshikoku@gmail.com

Core MLを使ったアプリを作っています。
機械学習関連の情報を発信しています。

Twitter
Medium
ホームページ

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4