我通过覆盖绘制矩形创建了一个蜘蛛图,我正在使用核心图形 CAShapeLayer 来绘制我的区域,在屏幕上创建了多个 CAShapeLayer 区域,我想检测用户触摸时触摸了哪个图层......但是我想不通怎么办?
问问题
4625 次
2 回答
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;
}
}
}
}
}
于 2012-04-14T16:58:08.527 回答
0
为了快速回答,这是在触摸开始时的 beginTracking,您还可以实现 continueTracking 以防您要继续跟踪什么。
它是如何工作的,您在 beginTracking 中获取触摸位置并检查,您的图层框架包含您触摸的点,如果是,它将打印语句。同样的方式你可以检查你的所有图层
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")
}
}
于 2018-07-08T14:25:48.370 回答