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

Posted

技术标签:

【中文标题】如何使用 UIViewAnimationOptionRepeat 自动重复一组链接的 UIView 动画【英文标题】:How to autorepeat a set of chained UIView animations using UIViewAnimationOptionRepeat 【发布时间】:2014-04-29 09:37:25 【问题描述】:

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

    UIView 向左设置 100 像素的动画 淡出UIView(不透明度'0') 淡出(不可见)时,将其移回原始位置(向右 100 像素) 将UIView 淡入(将不透明度设置为'1') 使用标志UIViewAnimationOptionRepeat重复动画

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

我试过的代码是这样的:

[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】:

问题是使用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

【讨论】:

但我无法随时使用 view.layer [removeAllAnimations] 停止它 @AvnerBarr 好的,已为您解决。 酷——所以只需创建一个机制来启动和停止递归动画 @AvnerBarr performSelector 在 Swift 中似乎不可用。你怎么能在 Swift 中链接重复的 UIView 动画?

以上是关于如何使用 UIViewAnimationOptionRepeat 自动重复一组链接的 UIView 动画的主要内容,如果未能解决你的问题,请参考以下文章

如何使用本机反应创建登录以及如何验证会话

如何在自动布局中使用约束标识符以及如何使用标识符更改约束? [迅速]

如何使用 AngularJS 的 ng-model 创建一个数组以及如何使用 jquery 提交?

如何使用laravel保存所有行数据每个行名或相等

如何使用 Math.Net 连接矩阵。如何使用 Math.Net 调用特定的行或列?

WSARecv 如何使用 lpOverlapped?如何手动发出事件信号?