今回の内容
コードと簡単解説
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)
}
}
終わり
ご指摘、ご質問などありましたら、コメントまでお願い致します。