LoginSignup
1
2

More than 3 years have passed since last update.

UITapGestureRecognizer どこでもTap swift

Last updated at Posted at 2021-05-23

■UITapGestureRecognizer とは

指定した場所でTapActionを行えるようにするもの

これによりbutton以外の場所でもTapを行えるようにする事ができる。

以下のようなアクションに対応させることが可能

■ピンチ
■パン (ドラックのこと)
■スワイプ
■ローテート(回転)
■ロングプレス(長押し)
■エッジ (スワイプで前の画面へ)

今回は基本的なタップでの処理をご紹介します。

まず全体のコードはこちら

■準備
今回はstoryboardにviewを一つ作りview1として繋げます。

import UIKit

class ViewController: UIViewController {

    @IBOutlet private weak var view1: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        view1.backgroundColor = .green
        let tapAction = UITapGestureRecognizer(target: self, action: #selector(viewTap(sender:)))
        view1.addGestureRecognizer(tapAction)
    }

    @objc private func viewTap(sender: UITapGestureRecognizer) {

        if view1.backgroundColor == UIColor.green {
            view1.backgroundColor = .blue
        } else {
            view1.backgroundColor = .green
        }
    }
}

コードの説明

let tapAction = UITapGestureRecognizer(target: self, action: #selector(viewTap(sender:)))

tap処理としてUITapGestureRecognizerを書きtargetをselfにしてactionにメソッドを書く
tapしたらそのメソッドを発動するよ

view1.addGestureRecognizer(tapAction)

view1にtapActionを登録

 @objc private func viewTap(sender: UITapGestureRecognizer) {

        if view1.backgroundColor == UIColor.green {
            view1.backgroundColor = .blue
        } else {
            view1.backgroundColor = .green
        }
    }

tapされたタイミングでメソッドの中身が発動
view1が緑なら青に
view1が緑意外なら緑に

結果

buttonを使わずにコードでtapActionを行えるようになりました。
UITapGestureRecognizerを使えば好きな場所でbuttonを使わずにtapActionを行えますね!!

UItap.gif

1
2
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
1
2