以下代码从屏幕顶部生成一个形状图像的动画,并使用核心动画向下漂移。当用户点击时,它将记录用户是否点击了图像(形状)或者他们是否错过了形状并因此触摸了背景。这似乎工作正常。然而,当我添加其他形状的图像时呢?我正在寻找有关如何构建此代码的建议,以便记录更详细的信息。
假设我想以编程方式添加三角形的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)
无论我多少尝试循环浏览我的视图和图层,我似乎都无法使其工作。我觉得我可能只是错过了一些明显的东西......
答案 0 :(得分:0)
我认为罪魁祸首是您更改thePoint
坐标系的行。它应该在执行该行之前读取convertPoint:fromLayer:
,你的点在self.view的坐标系中,我假设你希望它在imaveView的坐标系中。或者,您可以完全跳过该行并改为呼叫[t locationInView:_imageView]
。