3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

タップジェスチャをコールバックで(swift3)

Posted at

会社の人からタップジェスチャをコールバックで書けるpodのframeworkが便利って聞いたので、独自実装メモ。

自分の中で今後UIViewの代わりにUIViewを継承したclassを作成。
で、そこにタップジェスチャの定義とコールバックの定義を追加して、UIViewControllerから利用する。

まずはUIViewを継承して自分用のViewクラス

import UIKit
///
/// ベースビュー
///
class V: UIView, UIGestureRecognizerDelegate {
    
    
    // MARK: ------------------------------ UIGestureRecognizer
    ///
    /// コールバック関数
    ///
    private var _singleTapAction: ((_ g: UITapGestureRecognizer) -> Void)?
    ///
    /// シングルタップ設定
    ///
    func singleTap(_ action: ((_ g: UITapGestureRecognizer) -> Void)?) {
        let singleTapGesture: UITapGestureRecognizer = UITapGestureRecognizer(
            target: self,
            action: #selector(V._singleTapSelector(_:))
        )
        singleTapGesture.delegate = self
        singleTapGesture.numberOfTapsRequired = 1
        singleTapGesture.numberOfTouchesRequired = 1
        self.addGestureRecognizer(singleTapGesture)
        self._singleTapAction = action
    }
    ///
    /// selector用
    ///
    @objc private func _singleTapSelector(_ g: UITapGestureRecognizer) {
        self._singleTapAction?(g)
    }

}

利用するUIViewController側

let view: V = V.init()
view.singleTap { (g) in
    if UIGestureRecognizerState.ended == g.state {
        ///
        /// 何か処理
        ///
    }
}

コールバックで書けた方が分かり易いかも。
ダルブタップやロングタップも追加してみようかな。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?