Swift CAShapeLayer detecting tap
Detecting a tap on a CAShapeLayer has changed from Swift 2. This tutorial will cover how you can detect a tap then run some code on the tap.
First of all create a new single view application, and change the code to the following. It will add a square CAShapeLayer to our tutorial app.
import UIKit class ViewController: UIViewController { let squareLayer = CAShapeLayer() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Add the square to our view let squareCenter = CGPoint(x: 200, y: 200) let square = squarePathWithCenter(center: squareCenter, side: 100) squareLayer.path = square.cgPath squareLayer.fillColor = UIColor.red.cgColor self.view.layer.addSublayer(squareLayer) } func squarePathWithCenter(center: CGPoint, side: CGFloat) -> UIBezierPath { let squarePath = UIBezierPath() let startX = center.x - side / 2 let startY = center.y - side / 2 squarePath.move(to: CGPoint(x: startX, y: startY)) squarePath.addLine(to: squarePath.currentPoint) squarePath.addLine(to: CGPoint(x: startX + side, y: startY)) squarePath.addLine(to: squarePath.currentPoint) squarePath.addLine(to: CGPoint(x: startX + side, y: startY + side)) squarePath.addLine(to: squarePath.currentPoint) squarePath.addLine(to: CGPoint(x: startX, y: startY + side)) squarePath.addLine(to: squarePath.currentPoint) squarePath.close() return squarePath } }
If you run the app you will see the following:
To detect a tap on the Red CAShapeLayer square simply add the following:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first let point = touch!.location(in: self.view) if squareLayer.path!.contains(point) { print ("We tapped the square") } }
This will get the first touch on the device. It then needs to get the point which are coordinates of the tap. We then check the squareLayer we declared earlier to see if it contains the coordinates from the point. If the square was tapped we simply print out “We tapped the square” to the console.
You can run the app to see this working and download the source code below.