【发布时间】:2015-10-17 00:28:34
【问题描述】:
我在为两个相同的 UIImageView 设置动画时遇到了最奇怪的问题。一个单独的事件触发这两个 UIImageViews 靠近另一个,我以以下方式对其进行动画处理:
CGFloat originalX = self.firstMatchImage.layer.position.x;
self.firstMatchImage.layer.position = CGPointMake(originalX + displacement, self.firstMatchImage.layer.position.y);
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.x"];
animation.fromValue = @(originalX);
animation.duration = .18;
[self.firstMatchImage.layer addAnimation:animation forKey:@"position.x"];
CGFloat originalXsecond = self.secondMatchImage.layer.position.x;
self.secondMatchImage.layer.position = CGPointMake(originalXsecond - displacement, self.secondMatchImage.layer.position.y);
CABasicAnimation *animationSecond = [CABasicAnimation animationWithKeyPath:nil];
animationSecond.fromValue = @(originalXsecond);
animationSecond.duration = .18;
[self.secondMatchImage.layer addAnimation:animationSecond forKey:nil];
这很好用。这些图像很容易相互移动。但是,我也有一个事件触发动画以使这些 UIImageviews 移回其原始位置。为此,在我的故事板控制器的 viewDidLoad 方法中,我捕获了它们的基本位置:
firstImageOrigin = self.firstMatchImage.center;
secondImageOrigin = self.secondMatchImage.center;
因此,在将这些 UIImageViews 移回的方法调用中,我执行以下操作:
CGFloat originalX = self.firstMatchImage.layer.position.x;
self.firstMatchImage.layer.position = firstImageOrigin;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:nil];
animation.fromValue = @(originalX);
animation.duration = .18;
[self.firstMatchImage.layer addAnimation:animation forKey:nil];
CGFloat originalXsecond = self.secondMatchImage.layer.position.x;
self.secondMatchImage.layer.position = secondImageOrigin;
CABasicAnimation *animationSecond = [CABasicAnimation animationWithKeyPath:nil];
animationSecond.fromValue = @(originalXsecond);
animationSecond.duration = .19;
[self.secondMatchImage.layer addAnimation:animationSecond forKey:nil];
令我不快的是,只有名为 firstImageView 的 UIImageView 正确地向后移动。它适用于第一个图像,但第二个 UIImageView(self.secondMatchImage) 的行为方式不同,它会动画并移动一点,但不会回到原来的位置。结果如下:
我尝试将 keyPaths 命名为 nil 以外的其他名称,但是当我触发点击手势时,如果我命名了 keyPaths,它会使应用程序崩溃。我已经在 iPhone 和模拟器上对此进行了测试——同样的行为。我在这里超级难过。
任何关于这是如何发生的见解都会非常棒!谢谢!
【问题讨论】:
标签: ios objective-c cocoa-touch animation uiimageview