7 Stimmen

Wie kann man eine Kette von blockbasierten Animationen am besten anhalten?

Angenommen, eine Kette von blockbasierten Animationen wie die folgende:

UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];

//animation 1
[UIView animateWithDuration:2 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
     view.frame = CGRectMake(0, 100, 200, 200);
} completion:^(BOOL finished){

     //animation 2
     [UIView animateWithDuration:2 delay:0 options: UIViewAnimationOptionRepeat |UIViewAnimationOptionAutoreverse animations:^{
          [UIView setAnimationRepeatCount:1.5];
          view.frame = CGRectMake(50, 100, 200, 200);   
     } completion:^(BOOL finished){

          //animation 3
          [UIView animateWithDuration:2 delay:0 options:0 animations:^{
               view.frame = CGRectMake(50, 0, 200, 200);
          } completion:nil];
     }];
}];

Wie kann man diese Art von Animation am besten stoppen? Einfach aufrufen

[view.layer removeAllAnimations];

reicht nicht aus, denn dadurch wird nur der aktuell ausgeführte Animationsblock gestoppt und die übrigen werden nacheinander ausgeführt.

11voto

Jesse Rusak Punkte 55372

Sie können die finished BOOL, das an Ihre Abschlussblöcke übergeben wird. Es wird NO sein, wenn Sie die Funktion removeAllAnimations .

8voto

Ich verwende den folgenden Ansatz:

UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];

//set the animating flag
animating = YES;

//animation 1
[UIView animateWithDuration:2 delay:0 options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction animations:^{
     view.frame = CGRectMake(0, 100, 200, 200);
} completion:^(BOOL finished){
     //stops the chain
     if(! finished) return;

     //animation 2
     [UIView animateWithDuration:2 delay:0 options: UIViewAnimationOptionRepeat |UIViewAnimationOptionAutoreverse | UIViewAnimationOptionAllowUserInteraction  animations:^{
          [UIView setAnimationRepeatCount:1.5];
          view.frame = CGRectMake(50, 100, 200, 200);   
     } completion:^(BOOL finished){
          //stops the chain
          if(! finished) return;

          //animation 3
          [UIView animateWithDuration:2 delay:0 options:0 animations:^{
               view.frame = CGRectMake(50, 0, 200, 200);
          } completion:nil];
    }];
}];

- (void)stop {
     animating = NO;
     [view.layer removeAllAnimations];
}

Mit der Nachricht removeAllAnimations wird der Animationsblock sofort gestoppt und sein Abschlussblock aufgerufen. Dort wird das Animationsflag geprüft und die Kette angehalten.

Gibt es einen besseren Weg, dies zu tun?

CodeJaeger.com

CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.

Powered by:

X