LoginSignup
0
0

More than 1 year has passed since last update.

画面をタップしたことを検知して処理をさせる。(UITapGestureRecognizer( ))

Last updated at Posted at 2021-09-09

今回の内容

EE2BE1EC-8F38-41FF-B809-1187B4659E81_1_201_a.jpeg 5BAD35B0-115E-4AAE-80A1-5266D42A916D_1_201_a.jpeg

コードと簡単解説

  • UITapGestureRecognizer(target: self, action: #selector(メソッド名))でタップ時の処理を作成します。

  • viewなど.addGestureRecognizer(インスタンス)でタップした時に処理が働くようになります。

ViewController
import UIKit

class ViewController: UIViewController {


    @IBOutlet weak var detectionResultLabel: UILabel!

    var gradient = CAGradientLayer()
    var tapCount = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        gradient.frame = CGRect(x: self.view.frame.minX, y: self.view.frame.minY, width: self.view.frame.size.width, height: self.view.frame.size.height)

        let tapDetection = UITapGestureRecognizer(target: self, action: #selector(screenTap))
        view.addGestureRecognizer(tapDetection)

    }

    @objc func screenTap(){

        tapCount += 1
        detectionResultLabel.text = "\(tapCount)回、画面をタップしました"

        gradient.colors = [

                        UIColor(red: CGFloat.random(in: 0...255) / 255,
                                green:CGFloat.random(in:0...255) / 255,
                                blue: CGFloat.random(in: 0...255) / 255,
                                alpha: CGFloat.random(in: 0.0...1.0)).cgColor,
                        UIColor(red: CGFloat.random(in: 0...255) / 255,
                                green:CGFloat.random(in: 0...255) / 255,
                                blue: CGFloat.random(in: 0...255) / 255,
                                alpha: CGFloat.random(in: 0.0...1.0)).cgColor
                    ]

                    gradient.startPoint = CGPoint(x: 0.5, y: 0.5)
                    gradient.endPoint = CGPoint(x: 0.5, y: 0)
                    self.view.layer.insertSublayer(gradient, at: 0)    
    }

}

終わり

ご指摘、ご質問などありましたら、コメントまでお願い致します。

0
0
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
0
0