所以我一直在寻找,我还没有找到我想要的东西.
我有一个视图,然后是该视图的子视图.在第二个视图中,我根据我给它的坐标创建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; } }
我仍然是这个东西的初学者.我想知道是否有人能告诉我如何做到这一点.谢谢你的帮助.
解决方法
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 } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。