2010-11-13 150 views
3

所以我一直在寻找所有,我还没有完全找到我在找什么。触摸CALayer时触发一个动作?

我有一个视图,然后是该视图的子视图。在第二个视图中,我根据我给出的坐标创建了CALayers。我希望能够触摸任何这些CALayers并触发某些事物。

我发现不同的代码看起来像他们可以帮助,但我一直没有能够实现它们。

例如:

-(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; 

} } } 

而且这个....

- (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; 
    }  
} 

我还是很值得初学者到这个东西。我想知道是否有人能告诉我如何做到这一点。谢谢你的帮助。

回答

13

CALayer无法直接对触摸事件作出反应,但程序中可能有很多其他对象 - 例如托管图层的UIView。

事件,例如触摸屏幕时由系统生成的事件,正在通过所谓的“响应者链”发送。所以当触摸屏幕时,会向位于触摸位置的UIView发送一条消息(换句话说,称为方法)。触摸有三种可能的消息:touchesBegan:withEvent:,touchesMoved:withEvent:touchesEnded:withEvent:

如果该视图没有实现该方法,系统会尝试将其发送到父视图(iOS语言的超级视图)。它试图将它发送到顶部视图。如果没有任何视图实现该方法,它会尝试传递给当前的视图控制器,然后是父控制器,然后传递给应用程序对象。

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

让我们假设你在视图中实现它。接下来的任务是找出哪些图层已被触摸,为此您可以使用方便的方法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 
     } 
    } 
} 
+0

这条线:[self.secondView.layer convertPoint:P toLayer:pointLayer]我收到一个错误,指出:“不兼容类型对'containsPoint'的参数1有任何想法我应该做什么或出了什么问题? – 2010-11-14 19:27:54

+0

您需要确保您将CGPoint传递给containsPoint :.如果您不确定,请使用中间局部变量。 – 2011-12-04 17:39:34