0

i'm new to Objective-C and Xcode... I'm following a tutorial that explain how to move a car(a ImageView) to the top of the screen, rotate it, an then back to the bottom of the display.

This is the code:

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

The problem is that the car moves to the top, but then it's position is resetted at the bottom of the screen, like the center was resetted to the default center value, and only then is rotated.. I can't find a solution, need your help!

4

2 回答 2

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.

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

于 2013-09-22T23:27:47.530 回答
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]; }
 ];

谢谢

于 2013-09-23T11:03:26.807 回答