2

How do you find the actual layer that was hit?

At the moment I have numerous CAShapeLayers, and I want each one to do something when it is tapped. But when any one of them is tapped, an action happens to all of them.

This is my code so far:

    if shape.hitTest(point) != nil {
        shape.lineWidth = 60
    }
    if shape1.hitTest(point) != nil {
        shape1.lineWidth = 60
    }
    if shape2.hitTest(point) != nil {
        shape2.lineWidth = 60
    }

This probably means that it is only checking to see if the point tapped is a CAShapeLayer. How do you get it to check if the point tapped is a specific CAShapeLayer?

Jay Bhalani
  • 4,142
  • 8
  • 37
  • 50
John
  • 139
  • 1
  • 1
  • 11

1 Answers1

4

This should work:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    // Declare the touched symbol and its location on the screen
    for touch: AnyObject in touches {

        //get the point location
        let location:CGPoint = (touch as! UITouch).locationInView(self.view)

        if CGPathContainsPoint(shape1.path, nil, location, false) //shape 1
        {
            //touch in shape 1
        }
        else if CGPathContainsPoint(shape2.path, nil, location, false) //shape 2
        {
            //touch in shape 2
        }
        else if CGPathContainsPoint(shape3.path, nil, location, false) //shape 3
        {
            //touch in shape 3
        }
    }

}
Dejan Skledar
  • 11,280
  • 7
  • 44
  • 70