こちらの#selectorと@objcを使わずにかけるActionClosurableをよく使うのですが、その際にいつもGestureRecognizerで訳わからなくなるのでメモ。
https://github.com/takasek/ActionClosurable
やりたいこと
・UIViewにタップしたら(画面遷移などの)Action()
・UIViewをx秒以上ロングタップするとViewがグレーに代わり、話すとAction()
各単語の意味合い
Selector・・・actionの指定先である@objcで書いた時のメソッド名
Gesture・・・ユーザーの動作
GestureRecognizer・・・動作を認識する認識器
sender・・・Gestureを送るオブジェクト(UIButtonなど)
UIViewにTapとLongPressジェスチャーを付けるサンプルコード
func addTapGesture(action: @escaping () -> Void) {
let tapGesture = UITapGestureRecognizer { (gr) in
print("UITapGestureRecognizer fire")
switch gr.state {
case .ended:
self.backgroundColor = UIColor.clear
action()
default:
return
}
}
let longPressGesture = UILongPressGestureRecognizer { (gr) in
print("UILongPressGestureRecognizer fire")
switch gr.state {
case .began:
self.backgroundColor = UIColor.lightGray
case .ended:
self.backgroundColor = UIColor.clear
action()
default:
return
}
}
longPressGesture.minimumPressDuration = 0.05
longPressGesture.cancelsTouchesInView = false
self.addGestureRecognizer(tapGesture)
self.addGestureRecognizer(longPressGesture)
}
参考URL
https://developer.apple.com/documentation/uikit/uitapgesturerecognizer
https://i-app-tec.com/ios/uigesturerecognizer.html