Detecting a tap on a CAShapeLayer in Swift?
Swift 4 & 5
My UIImageView
has multiple embedded CAShapeLayer
objects. Here is how I was able to detect taps on them. Referenced from this tutorial.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
guard let point = touch?.location(in: imageView) else { return }
guard let sublayers = imageView.layer.sublayers as? [CAShapeLayer] else { return }
for layer in sublayers {
if let path = layer.path, path.contains(point) {
print(layer)
}
}
}
I used Arbitur's code and i had some errors. Here is a code i had with no errors. For swift 3.2 / 4.0
override func viewDidLoad() {
super.viewDidLoad()
let layer = CAShapeLayer()
layer.anchorPoint = CGPoint.zero
layer.path = UIBezierPath.init(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 200)).cgPath
layer.bounds = (layer.path?.boundingBox)! // IMPORTANT, without this hitTest wont work
layer.fillColor = UIColor.red.cgColor
self.view.layer.addSublayer(layer)
}
// Check for touches
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let point = touches.first?.location(in: self.view) // Where you pressed
if let layer = self.view.layer.hitTest(point!) as? CAShapeLayer { // If you hit a layer and if its a Shapelayer
if (layer.path?.contains(point!))! { // Optional, if you are inside its content path
print("Hit shapeLayer") // Do something
}
}
}
Heres imo the best way to do what you want to achieve:
// First add the shapelayer
let layer = CAShapeLayer()
layer.anchorPoint = CGPointZero
layer.path = UIBezierPath(ovalInRect: CGRect(x: 0, y: 0, width: 100, height: 200)).CGPath
layer.bounds = CGPathGetBoundingBox(layer.path) // IMPORTANT, without this hitTest wont work
layer.fillColor = UIColor.redColor().CGColor
self.view.layer.addSublayer(layer)
// Check for touches
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let point = touches.anyObject()!.locationInView(self.view) // Where you pressed
if let layer = self.view.layer.hitTest(point) as? CAShapeLayer { // If you hit a layer and if its a Shapelayer
if CGPathContainsPoint(layer.path, nil, point, false) { // Optional, if you are inside its content path
println("Hit shapeLayer") // Do something
}
}
}