Cocoa touch 在处理各种移动的子视图时,如何检测所接触的子视图?

Cocoa touch 在处理各种移动的子视图时,如何检测所接触的子视图?,cocoa-touch,uiview,core-animation,calayer,uitouch,Cocoa Touch,Uiview,Core Animation,Calayer,Uitouch,下面的代码从屏幕顶部生成形状图像的动画,并使用核心动画向下漂移。当用户点击时,它将记录用户是否点击了图像(形状),或者是否错过了形状并因此触摸了背景。这似乎很有效。但是,当我添加其他形状的图像时会怎么样?我正在寻找关于如何构建此代码以允许记录更多详细信息的建议 假设我想以编程方式添加三角形的UIImage、正方形的UIImage和圆形的UIImage。我希望所有这三幅图像开始从上到下漂移。它们甚至可能在过渡时相互重叠。我希望能够记录“你触到了正方形!”或任何我触到的合适形状。我希望能够这样做,即

下面的代码从屏幕顶部生成形状图像的动画,并使用核心动画向下漂移。当用户点击时,它将记录用户是否点击了图像(形状),或者是否错过了形状并因此触摸了背景。这似乎很有效。但是,当我添加其他形状的图像时会怎么样?我正在寻找关于如何构建此代码以允许记录更多详细信息的建议

假设我想以编程方式添加三角形的UIImage、正方形的UIImage和圆形的UIImage。我希望所有这三幅图像开始从上到下漂移。它们甚至可能在过渡时相互重叠。我希望能够记录“你触到了正方形!”或任何我触到的合适形状。我希望能够这样做,即使正方形位于三角形和圆之间,但部分正方形正在显示,以便我可以点击它。(这个例子表明我不仅仅想与最顶层交互)

如何调整此代码以编程方式添加不同的UIImage(可能是各种形状的图像),并能够记录我正在触摸的形状

- (void)viewDidLoad
 {
 [super viewDidLoad];

 CGPoint endPoint = CGPointMake([[self view] bounds].size.width, 
                             [[self view] bounds].size.height);
 CABasicAnimation *animation = [CABasicAnimation 
                                    animationWithKeyPath:@"position"];
 animation.fromValue = [NSValue valueWithCGPoint:[[_imageView layer] position]];
 animation.toValue = [NSValue valueWithCGPoint:endPoint];
 animation.duration = 30.0f;
 [[_imageView layer] addAnimation:animation forKey:@"position"];

 }



 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 {
 UITouch *t = [touches anyObject];
 CGPoint thePoint = [t locationInView:self.view];

   thePoint = [[_imageView layer] convertPoint:thePoint toLayer:[[self view] layer]];

      if([[_imageView layer].presentationLayer hitTest:thePoint])
         {
             NSLog(@"You touched a Shape!");
             // for now I'm just logging this information.  Eventually I want to have the shape follow my figure as I move it to a new location.  I want everything else to continue animating but I when I touch a particular shape I want to have complete control on repositioning that specific shape.  That's just some insight beyond the scope of this question.  However feel free to comment about this if you have suggestions.  

         }
         else{
             NSLog(@"backgound touched");
         }

   }

我认为这个问题的答案可能与循环不同的子视图有关。看看我是怎么想的,我可能会改变-touchesbeated方法:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *t = [t anyObject];
    CGPoint thePoint = [t locationInView:self.view];
    for (UIView *myView in viewArray) {
        if (CGRectContainsPoint(myView.frame, thePoint)) {....
请注意,我在这里设置了一个viewArray,并将所有子视图都放在了viewArray中。这是我应该用的东西吗?或者,如果我要在我的层中循环,可能类似于以下内容:

 for(CALayer *mylayer in self.view.layer.sublayers)

无论我如何尝试在我的视图和/或层中循环,我似乎都无法实现这一点。我觉得我可能只是错过了一些明显的东西…

我认为罪魁祸首是你改变点坐标系的那条线。它应该读作
convertPoint:fromLayer:
,因为在执行该行之前,您的点位于self.view的坐标系中,我假设您希望它位于imaveView的坐标系中。或者,您可以完全跳过该行并调用
[t locationInView:\u imageView]