【问题标题】:Stop specific UIViewAnimation block - iOS停止特定的 UIViewAnimation 块 - iOS
【发布时间】:2015-07-08 06:23:31
【问题描述】:

我有一个 iOS 应用程序,它运行几个不同的 UIViewAnimation 块来为屏幕上的几个不同对象设置动画。这一切都有效,但我怎样才能停止其中一个动画块而不停止其余部分?

我尝试过使用以下方法:

[button.layer removeAllAnimations];

但它什么也没做,动画只是继续。

然后,我尝试使用一个简单的 BOOL 值,并在 BOOL 设置为“NO”后从该方法将动画设置为 return,但这也不起作用。

这是我要停止的动画:

-(void)undo_animation:(int)num {

    // Fade out/in the number button label
    // animation which lets the user know
    // they can undo this particular action.

    [UIView animateWithDuration:0.5 delay:0.2 options:(UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionAllowUserInteraction) animations:^{

        // Mostly fade out the number button label.
        ((UIButton *)_buttons[num]).alpha = 0.2;

    } completion:^(BOOL finished) {

        [UIView animateWithDuration:0.5 delay:0.2 options:(UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionAllowUserInteraction) animations:^{

            // Fade in the number button label.
            ((UIButton *)_buttons[num]).alpha = 1.0;

        } completion:^(BOOL finished) {

            // Stop the animation if the BOOL
            // is set to 'NO' animations.

            if (anim_state_button == NO) {
                return;
            }
        }];
    }];
}

谢谢,丹。

【问题讨论】:

  • 试试[self.view removeAllAnimations];
  • @Mrunal 出现错误,我不知道removeAllAnimations 方法在self.view 上可用。

标签: ios objective-c animation uiviewanimation animatewithduration


【解决方案1】:

如果您使用 UIKit 动画,则无法访问运行动画属性。因此,如果您想在运行时修改动画,我建议使用 Core Animation。

像下面这样删除视图的 alpha 太简单了。

CABasicAnimation* fadein= [CABasicAnimation animationWithKeyPath:@"opacity"];
[fadein setToValue:[NSNumber numberWithFloat:1.0]];
[fadein setDuration:0.5];
[[moviepic layer]addAnimation:fadein forKey:@"MyAnimation"]; 

将动画添加到图层后,动画将开始,然后您可以使用委托方法来了解 animationDidFinish: 方法

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
{
    NSLog(@"Animation interrupted: %@", (!flag)?@"Yes" : @"No");
}

您也可以随时随地使用;

[[moviepic layer] animationForKey:@"MyAnimation"];

当然,您需要将 CoreAnimation 框架添加到您的项目中。

希望对你有帮助。

【讨论】:

  • 我还需要包含CoreAnimation 框架才能使此方法起作用吗?
【解决方案2】:

我认为简单的方法是从视图层中删除所有动画,因为所有动画默认添加到视图层中。

[yourRequiredView.layer removeAllAnimations]; 

【讨论】:

    【解决方案3】:

    我的理解是,从相关图层中删除所有动画应该会停止所有动画。 [((UIButton *)_buttons[num]).layer removeAllAnimations]; 怎么样?

    【讨论】:

    • 如果您使用 uiview 动画,您不会将其添加到图层,这就是无法从图层中删除动画的原因。
    • @mert。您(程序员)没有直接将动画添加到任何层是正确的,但我的印象是 UIView 动画实际上确实将 CAAnimations 添加到幕后的任何相关层。
    • 在您回复后,我深入研究了 UIView 的机制,您说得对,确实 UIView 动画正在使用 CALayer 进行更改。从苹果文档中发现 因为 iOS 视图总是有一个底层,所以 UIView 类本身直接从层对象中派生大部分数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 2011-12-08
    • 2018-02-25
    相关资源
    最近更新 更多