以下代码从屏幕顶部生成形状图像的动画,并使用核心动画向下漂移。当用户点击时,它会记录用户是否点击了图像(形状),或者他们是否错过了形状并因此触摸了背景。这似乎工作正常。但是,当我添加其他形状的图像时呢?我正在寻找有关如何构建此代码以允许记录更详细信息的建议。
假设我想以编程方式添加三角形的 UIImage、正方形的 UIImage 和圆形的 UIImage。我希望所有三个图像都开始从上到下漂移。它们甚至可能在过渡时相互重叠。我希望能够记录“你触动了广场!” 或者我接触过的任何合适的形状。即使正方形位于三角形和圆形之间,我也希望能够这样做,但正方形的一部分正在显示,所以我可以点击它。(这个例子表明我不只是想与最顶层交互)
如何调整此代码以编程方式添加不同的 UIImages(可能是各种形状的图像)并能够记录我正在触摸的形状?
- (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");
}
}
我在想这个问题的答案可能与循环各种子视图有关。看看我怎么想我可能会改变 -touchesBegan 方法:
- (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)
无论我如何尝试循环浏览我的视图和/或图层,我似乎都无法让它工作。我觉得我可能只是错过了一些明显的东西......