CGPoint中心动画由CGAffineTransform“无效”

时间:2013-09-22 22:12:12

标签: objective-c ios7 cgaffinetransform

我是Objective-C和Xcode的新手...我正在按照一个教程解释如何将汽车(一个ImageView)移动到屏幕顶部,旋转它,然后回到底部显示器。

这是代码:

- (IBAction)testDrive:(id)sender {
      CGPoint center = CGPointMake(_car.center.x, self.view.bounds.origin.y + _car.bounds.size.height/2 +100);
      [UIView animateWithDuration:3
        animations:^ { _car.center = center;}
        completion:^(BOOL finished){[self rotate];}]; 
}

- (void) rotate{
      CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI);

      void (^animation)() = ^() { _car.transform = transform;
      };

      void (^completion)(BOOL) = ^(BOOL finished){
        [self returnCar];
      };
     [UIView animateWithDuration:3 animations:animation completion:completion];
}

问题是汽车移动到顶部,但是它的位置被重置在屏幕的底部,就像中心被重置为默认的中心值,然后才旋转..我找不到一个解决方案,需要你的帮助!

2 个答案:

答案 0 :(得分:1)

当你做动画时,它的效果是暂时的,默认情况下它们实际上不会改变你的图层/视图。通常,您会明确地将“结束”值写入完成块中的层/视图中。您需要为动画“链”中的每个动画执行此操作。使用您的代码,我怀疑如果您这样做,您将获得理想的结果:

- (IBAction)testDrive:(id)sender {
      CGPoint center = CGPointMake(_car.center.x, self.view.bounds.origin.y + _car.bounds.size.height/2 +100);
      [UIView animateWithDuration:3
        animations:^ { _car.center = center;}
        completion:^(BOOL finished){ _car.center = center; [self rotate];}]; 
}

- (void) rotate{
      CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI);

      void (^animation)() = ^() { _car.transform = transform;
      };

      void (^completion)(BOOL) = ^(BOOL finished){
        _car.transform = transform;
        [self returnCar];
      };
     [UIView animateWithDuration:3 animations:animation completion:completion];
}

您还希望在-returnCar中进行相应的更改。

这里的想法是动画只影响“表示层”而不影响“模型层”。如果您希望模型图层反映动画的“之后”状态,则需要明确地执行此操作。

答案 1 :(得分:0)

经过几个小时的打击后,我找到了解决这个问题的方法,这是由于AutoLayout造成的。

这是工作代码

self.topConstraint.constant = self.topConstraint.constant-self.topConstraint.constant;
[self.car setNeedsUpdateConstraints];  // 2
[UIView animateWithDuration:3
        animations:^{
                        [self.car layoutIfNeeded]; // 3
                    }
        completion:^(BOOL finished){[self rotate]; }
 ];

由于