0

The code below came from this SO question: UIView shake animation.

This shake animation is perfect, except it stops after one iteration. How do you repeat the animation indefinitely, or how do you cause it to repeat it X times?

There are other SO answers on repeating UIView animations that suggest using CAKeyframeAnimation or CABasicAnimation, but this question is different. The goal is to reproduce this exact animation, with the "springy" effect from usingSpringWithDamping and initialSpringVelocity.

Using Autoreverse and Repeat don't reproduce the desired effect because the the initial translation is outside the animation block.

view.transform = CGAffineTransformMakeTranslation(20, 0);
[UIView animateWithDuration:0.4 delay:0.0 usingSpringWithDamping:0.2 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
    view.transform = CGAffineTransformIdentity;
} completion:nil];
Community
  • 1
  • 1
Crashalot
  • 33,605
  • 61
  • 269
  • 439

2 Answers2

0

If you need exact same code few times than put that code in method and do recursion, something like that:

- (void)animateCount:(NSInteger)count {
   if (count == 0) {
      return;
   }

   view.transform = CGAffineTransformMakeTranslation(20, 0);
   [UIView animateWithDuration:0.4 delay:0.0 usingSpringWithDamping:0.2 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
      view.transform = CGAffineTransformIdentity;
   } completion:^{
      count--;
      [self animateCount:count];
   }];
}
Konstantin
  • 861
  • 4
  • 12
0

Use (UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat) in options to repeat it indefinitely

[UIView animateWithDuration:0.4 delay:0.0 usingSpringWithDamping:0.2 initialSpringVelocity:1.0 options:(UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveEaseInOut) animations:^{

    someView.frame = someFrame1;

} completion:^(BOOL finished) {

    [UIView animateWithDuration:0.5f animations:^{

        someView.frame = someFrame2;

    } completion:nil];

}]; 
Ali Baqbani
  • 153
  • 1
  • 2
  • 13