【Swift/UIKit】タップ・長押し・スワイプを認識させる
いくつかある UIGestureRecognizer の中からタップ・長押し・スワイプの実装方法をメモ。それぞれの細かいプロパティについては割愛して、とりあえず動くところまでをば。
UITapGestureRecognizer(タップ)
インスタンスを生成。
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
任意の View に追加。
view.addGestureRecognizer(tapGesture)
タップを検知した時に呼ばれるメソッドを記述。
@objc func tapped(_ sender: UITapGestureRecognizer) { if sender.state == .ended { print("tapped") } }
UILongPressGestureRecognizer(長押し)
インスタンスを生成。
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(_:))
任意の View に追加。
view.addGestureRecognizer(longPressGesture)
長押しを検知した時に呼ばれるメソッドを記述。
@objc func longPressed(_ sender: UILongPressGestureRecognizer) { if sender.state == .began { //長押し開始 print("began press") } else if sender.state == .ended { //長押し終了 print("ended press") } }
UISwipeGestureRecognizer(スワイプ)
インスタンスを生成。SwipeGestureRecognizer は、上下左右それぞれ別々のインスタンスが必要。右スワイプだけ必要な場合は、右スワイプのインスタンスだけを作る。ここでは、4つまとめて書き残しておく。
//右へ let rightSwipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(swiped(_:))) rightSwipeGesture.direction = .right //左へ let leftSwipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(swiped(_:))) leftSwipeGesture.direction = .left //上へ let upSwipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(swiped(_:))) upSwipeGesture.direction = .up //下へ let downSwipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(swiped(_:))) downSwipeGesture.direction = .down
任意の view に追加。
view.addGestureRecognizer(rightSwipeGesture) view.addGestureRecognizer(leftSwipeGesture) view.addGestureRecognizer(upSwipeGesture) view.addGestureRecognizer(downSwipeGesture)
スワイプを検知した時に呼ばれるメソッドを記述。
@objc func swiped(_ sender: UISwipeGestureRecognizer) { switch sender.direction { case .left: print("swiped left") case .right: print("swiped right") case .up: print("swiped up") case .down: print("swiped down") default: break } }