检测CAShapeLayer触摸

use*_*444 9 ios

我通过覆盖draw rect创建了一个蜘蛛图表,我使用核心grahics CAShapeLayer绘制我的区域,在屏幕上创建了多个CAShapeLayer区域,我想检测用户触摸时触摸哪个图层...但是我弄不清楚怎么样?

Jod*_*ins 20

首先,您不应该在drawRect中绘制图层,但这不是您的问题.要识别"触摸"的图层,您可以执行以下操作...

- (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;
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)