触摸CALayer时触发一个动作?

所以我一直在寻找,我还没有find我要找的东西。

我有一个观点,然后是这个观点的子视图。 在第二个视图中,我根据我给出的坐标创buildCALayers。 我希望能够触摸任何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; } } 

我仍然是这个东西的初学者。 我想知道如果有人能告诉我如何做到这一点。 谢谢你的帮助。

CALayer不能直接对触摸事件做出反应,但是程序中还有许多其他的对象可以使用 – 例如UIView是托pipe图层的。

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

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

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

假设你在视图中实现它。 接下来的任务是找出你的图层被触摸,为此你可以使用方便的方法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 } } } 
Interesting Posts