LoginSignup
4
3

More than 5 years have passed since last update.

UIViewにActionClosurableを使ってタッチイベントを付ける方法

Last updated at Posted at 2018-10-17

こちらの#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

4
3
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
4
3