CABasicAnimation 处理一张图片,但不处理另一张图片

CABasicAnimation working on one image, but not another

我在为两个相同的 UIImageView 设置动画时遇到了最奇怪的问题。一个单独的事件触发这两个 UIImageView 被移近另一个,我用以下方式制作动画:

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];

这很好用。图像很容易相互移动。但是,我还有一个事件触发动画,使这些 UIImageview 移回其原始位置。为此,在我的故事板控制器的 viewDidLoad 方法中,我捕获了它们的基本位置:

firstImageOrigin = self.firstMatchImage.center;
secondImageOrigin = self.secondMatchImage.center;

因此,在将这些 UIImageView 移回的方法调用中,我执行以下操作:

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 和模拟器上对此进行了测试 - 相同的行为。我在这里超级难过。

任何关于这是如何发生的见解都将非常棒!谢谢!

事实证明,在控制器的 viewDidLoad 方法中获取图像的位置并不是理想的解决方案。相反,我将原始坐标设置为 CGPointMake(0,0)在 viewDidLoad 方法中并在我的动画方法中使用此登录:

 if (firstImageOrigin.x == 0 && firstImageOrigin.y == 0) {
    firstImageOrigin = self.firstMatchImage.center;
    secondImageOrigin = self.secondMatchImage.center;
}

现在它完美运行了!