user3857868
user3857868

Reputation:

CAShapeLayer Tapping

I'm using a CAShapeLayer to draw some shapes in the view. I made a function to manage this. So, for example:

in viewDidLoad()

drawQuad(UIColor(red: 0.600, green: 0.224, blue: 0.341, alpha: 1.00), firstPoint: CGPointMake(screenWidth * -0.159, screenHeight * 0.249), secondPoint: CGPointMake(screenWidth * 0.65, screenHeight * 0.249), thirdPoint: CGPointMake(screenWidth * 1.01, screenHeight * 0.50), fourthPoint: CGPointMake(screenWidth * 0.399, screenHeight * 0.50))

in drawQuad(...)

func drawQuad(fillColor: UIColor, firstPoint: CGPoint, secondPoint: CGPoint, thirdPoint: CGPoint, fourthPoint: CGPoint) {
    let screenWidth = screenSize.width
    let screenHeight = screenSize.height

    let shape = CAShapeLayer()
    containerLayer.addSublayer(shape)
    shape.lineJoin = kCALineJoinMiter
    shape.fillColor = fillColor.CGColor

    let path = UIBezierPath()
    path.moveToPoint(firstPoint)
    path.addLineToPoint(secondPoint)
    path.addLineToPoint(thirdPoint)
    path.addLineToPoint(fourthPoint)

    path.closePath()
    shape.path = path.CGPath
}

I'm getting stuck with trying to add tap recognition to each shape. What I tried to do was create a container CAShapeLayer that keeps each shape as a sublayer. If you look in the function above, you'll see this on line 6. Then, in viewDidLoad(), I added the final container layer to the view.

The point of doing that is to be able to do a hitTest like this:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    let touch = touches.first as! UITouch
    let location = touch.locationInView(self.view)

    for layer in containerLayer.sublayers {
        if let hitLayer = layer.hitTest(location) {
            println("Tapped")
        }
    }
}

Unfortunately, this doesn't seem to be working. Does anyone know the mistake I'm making? Or maybe I'm going about this the wrong way?

Thank you!

Upvotes: 1

Views: 613

Answers (1)

Vlad
Vlad

Reputation: 7260

Try to use CGPathContainsPoint to check whether a touch's location is contained in your layer's path.

Upvotes: 1

Related Questions