如何使用UIViewAnimationOptionRepeat自动重复一组链式UIView动画

时间:2014-04-29 09:37:25

标签: ios objective-c uiview uiviewanimation

我正在尝试使用标记UIView animateWithDuration:链接一组UIViewAnimationOptionRepeat 我想重复的动画步骤是:

  1. 向左侧UIView 100个像素设置动画
  2. 淡出UIView(不透明度'0'
  3. 逐渐淡出(不可见),将其移回原位(向右100 px)
  4. 淡化UIView(将不透明度设置为'1'
  5. 使用标记UIViewAnimationOptionRepeat
  6. 重复动画

    我无法重复整个动画链 - 只能重复最顶层的动画。

    我尝试的代码是:

    [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionRepeat animations:^{
            self.handImageView.frame = CGRectMoveByXPixels(self.handImageView.frame, -100);
            [UIView animateWithDuration:0.5 delay:1 options:0 animations:^{
                self.handImageView.alpha = 0;
            } completion:^(BOOL finished) {
                self.handImageView.frame = CGRectMoveByXPixels(self.handImageView.frame, 100);
                [UIView animateWithDuration:0.5 delay:0 options:0 animations:^{
                    self.handImageView.alpha = 1;
                } completion:^(BOOL finished) {
    
                }];
            }];
        } completion:^(BOOL finished) {
    
        }];
    

1 个答案:

答案 0 :(得分:1)

问题是使用UIViewAnimationOptionRepeat的动画永远不会完成,因此永远不会调用completion块。但是,您可以使用performSelector方法重复动画,如下面的代码所示。

- (void)repeatingAnimationForView:(UIView *)view
{
    [UIView animateWithDuration:1 delay:0 options:0
    animations:^{ view.frame = CGRectMoveByXPixels(view.frame, -100); }
    completion:^(BOOL finished) {  if ( finished )  {

    [UIView animateWithDuration:0.5 delay:0 options:0
    animations:^{ view.alpha = 0; }
    completion:^(BOOL finished) {  if ( finished )  {

    view.frame = CGRectMoveByXPixels(view.frame, 100);

    [UIView animateWithDuration:0.5 delay:0 options:0
    animations:^{ view.alpha = 1; }
    completion:^(BOOL finished) {  if ( finished )  {

    if ( self.enableRepeatingAnimation )
        [self performSelector:@selector(repeatingAnimationForView:) withObject:view afterDelay:0];

    }}]; }}]; }}];
}

- (void)stopRepeatingAnimationForView:(UIView *)view
{
    self.enableRepeatingAnimation = NO;
    [view.layer removeAllAnimations];
    view.frame = CGRectMake( 100, 137, 80, 50 );
    view.alpha = 1;
}

- (void)startRepeatingAnimationForView:(UIView *)view
{
    self.enableRepeatingAnimation = YES;
    [self repeatingAnimationForView:view];
}

要立即停止动画,请调用上面显示的stopRepeatingAnimationForView方法。要在周期结束时停止动画,只需将self.enableRepeatingAnimation设置为NO即可。