当触摸CALayer时触发一个动作?

3

我一直在寻找,但还没有找到我需要的答案。

我有一个视图和它的子视图。在第二个视图中,根据给定的坐标创建CALayers。我想能够触摸任何一个CALayer并触发某些操作。

我找到了不同的代码片段,看起来可以帮助我,但我还没有能够实现它们。

例如:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { if ([touches count] == 1) { for (UITouch *touch in touches) {

CGPoint point = [touch locationInView:[touch view]]; point = [[touch view] convertPoint:point toView:nil];

CALayer *layer = [(CALayer *)self.view.layer.presentationLayer hitTest:point];

layer = layer.modelLayer; layer.opacity = 0.5;

} } } 

and also this....

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];

    // If the touch was in the placardView, bounce it back to the center
    if ([touch view] == placardView) {
        // Disable user interaction so subsequent touches don't interfere with animation
        self.userInteractionEnabled = NO;
        [self animatePlacardViewToCenter];
        return;
    }       
}

我在这个领域还是一个新手,想知道如何做到这一点,有人可以告诉我吗?感谢任何帮助。

1个回答

14

CALayer无法直接对触摸事件做出反应,但是程序中的许多其他对象可以,例如托管图层的UIView。

事件(如当屏幕被触摸时由系统生成的事件)会被发送到所谓的“响应链”上。因此,当屏幕被触摸时,消息将被发送(换句话说,方法被调用)到位于触摸位置的UIView。对于触摸,有三个可能的消息:touchesBegan:withEvent:touchesMoved:withEvent:touchesEnded:withEvent:

如果该视图没有实现该方法,则系统将尝试将其发送到父视图(在iOS语言中为superview)。它会一直尝试发送到达顶部视图。如果没有视图实现该方法,则会尝试传递给当前视图控制器,然后是其父控制器,最后传递给应用程序对象。

这意味着您可以通过在这些对象中的任何一个中实现上述方法来对触摸事件做出反应。通常,托管视图或当前视图控制器是最佳选择。

假设你在视图中实现了它。下一步任务是找出已被触摸的图层,为此,您可以使用方便的方法convertPoint:toLayer:

例如,这是在视图控制器中的样子:

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    CGPoint p = [(UITouch*)[touches anyObject] locationInView:self.worldView];
    for (CALayer *layer in self.worldView.layer.sublayers) {
        if ([layer containsPoint:[self.worldView.layer convertPoint:p toLayer:layer]]) {
            // do something
        }
    }
}

我正在处理以下代码:[self.secondView.layer convertPoint:p toLayer:pointLayer],但是出现了一个错误:“'containsPoint'的参数1类型不兼容”。你有什么想法或者知道哪里出错了吗? - kernelpanic
你需要确保将CGPoint传递给containsPoint:。如果不确定,可以使用一个中间的本地变量。 - i_am_jorf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接