user1333444
user1333444

Reputation: 103

detect CAShapeLayer touch

I have created a spider chart by overiding draw rect, I am using core grahics CAShapeLayer to draw my areas, there are multiple CAShapeLayer regions which are created on the screen, I want to detect which layer is touched when the users touches... but I can't figure out how?

Upvotes: 9

Views: 4755

Answers (2)

Iraniya Naynesh
Iraniya Naynesh

Reputation: 1165

For swift answer This is beginTracking as the touch starts, you can also implement continueTracking in case you what to keep tracking.

How it works, you get the touch location inside the beginTracking and check, your layer frames contains the point you touch if yes it will print the statement. Same way you can check for all your layer

override open func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
     let loaction = touch.location(in: self)
     //update yourLayer with your layer name
     if yourLayer.frame.contains(previousLoaction) { 
        Print("Touch is inside yourLayer layer")
     }
}

Upvotes: 0

Jody Hagins
Jody Hagins

Reputation: 28409

First, you should not be drawing layers in drawRect, but that is not your question. To identify a layer that is "touched" you can do something like this...

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (UITouch *touch in touches) {
        CGPoint touchLocation = [touch locationInView:self.view];
        for (id sublayer in self.view.layer.sublayers) {
            BOOL touchInLayer = NO;
            if ([sublayer isKindOfClass:[CAShapeLayer class]]) {
                CAShapeLayer *shapeLayer = sublayer;
                if (CGPathContainsPoint(shapeLayer.path, 0, touchLocation, YES)) {
                    // This touch is in this shape layer
                    touchInLayer = YES;
                }
            } else {
                CALayer *layer = sublayer;
                if (CGRectContainsPoint(layer.frame, touchLocation)) {
                    // Touch is in this rectangular layer
                    touchInLayer = YES;
                }
            }
        }
    }
}

Upvotes: 20

Related Questions