Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

UIGestureRecognizer

More than 1 year has passed since last update.

タップ動作への理解を深めるために作成。

ezgif.com-video-to-gif

ソースコード

タップ動作はカウントされ
ロングタップは「LongPress」となるよう処理。

ViewController.swift
import UIKit

//タップを認識するためのメソッド
class ViewController: UIViewController,UIGestureRecognizerDelegate {


    @IBOutlet var label: UILabel!


    var count = 0


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //タップを認識するためのインスタンスを生成
        let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapped(_:)))

        //デリゲートをセット
        tapGesture.delegate = self

        self.view.addGestureRecognizer(tapGesture) //viewにインスタンスを追加

        //ロングプレス
        let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPress(_:)))

        longPressGesture.delegate = self
        //Viewに追加
        self.view.addGestureRecognizer(longPressGesture)
    }

    //tapイベント
    @objc func tapped(_ sender: UITapGestureRecognizer) {
        //送信者の状態が タッチして指を離した時に呼ばれる
        if sender.state == .ended {
            label.text = "Tapped!\(count)"
            count += 1
        }
        else if sender.state == .began {
            print("Tap began")
        }
    }

    //longpressイベント
    @objc func longPress(_ sender: UILongPressGestureRecognizer) {
        //送信者の状態が タッチ開始時にlongが認識される
        if sender.state == .began{
            //開始は認知される
            print("Long Press began")
        }
        else if sender.state == .ended {
            label.text = "Long Pressd !"
        }
    }
}

ロングプレス

UILongPressGestureRecognizer

タップの認識

UITapGestureRecognizer

mumei1
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away