CABasicAnimation处理一个图像,而不是另一个

时间:2015-07-26 22:32:04

标签: ios objective-c cocoa-touch animation uiimageview

我有两个相同的UIImageViews动画的最奇怪的问题。一个单独的事件触发这两个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移回原来的位置。为此,在我的storyboard控制器的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),行为方式不同,它动画和移动一点,但不回到原来的位置。这是结果如下: Left is good, right is bad

我已经将keyPaths命名为nil以外的东西,但是当我触发一个轻击手势时,如果我已经命名了keyPaths,它就会崩溃应用程序。我在iPhone和模拟器上测试了这个 - 同样的行为。我在这里非常难过。

任何关于如何发生这种情况的见解都会非常棒!谢谢!

1 个答案:

答案 0 :(得分:0)

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

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

现在它完美无缺!