是否有可能取消一个UIView动画,而它正在进行中?或者我必须降到CA级别?

例如,我做过这样的事情(可能设置了一个结束动画动作):

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:duration];
[UIView setAnimationCurve: UIViewAnimationCurveLinear];
// other animation properties

// set view properties

[UIView commitAnimations];

但是在动画完成之前,我得到动画结束事件,我想取消它(缩短它)。这可能吗?在谷歌上搜索一下,会发现一些人问了同样的问题,但没有答案——还有一两个人猜测这是不可能的。


当前回答

要取消一个动画,你只需要设置当前正在动画的属性,在UIView动画之外。那会停止动画,不管它在哪里,UIView会跳转到你刚刚定义的设置。

其他回答

Use:

#import <QuartzCore/QuartzCore.h>

.......

[myView.layer removeAllAnimations];

在一个特定的视图上立即停止所有动画的最简单的方法是:

将项目链接到QuartzCore.framework。在代码的开头:

#import <QuartzCore/QuartzCore.h>

现在,当你想停止视图中的所有动画时,这样说:

[CATransaction begin];
[theView.layer removeAllAnimations];
[CATransaction commit];

中线可以自己工作,但是在运行循环结束之前会有一个延迟(“重画时刻”)。为了防止这种延迟,可以将命令包装在显式事务块中,如图所示。如果在当前运行循环中没有对该层执行其他更改,则此工作正常。

如果你只是想平稳地暂停/停止动画

self.yourView.layer.speed = 0;

如何暂停一个层树的动画

没有一个解决方案对我有效。我用这种方式解决了我的问题(我不知道这是否是正确的方式?),因为我在调用这个太快的时候有问题(当以前的动画还没有完成的时候)。我通过customAnim块传递我想要的动画。

extension UIView
{

    func niceCustomTranstion(
        duration: CGFloat = 0.3,
        options: UIView.AnimationOptions = .transitionCrossDissolve,
        customAnim: @escaping () -> Void
        )
    {
        UIView.transition(
            with: self,
            duration: TimeInterval(duration),
            options: options,
            animations: {
                customAnim()
        },
            completion: { (finished) in
                if !finished
                {
                    // NOTE: This fixes possible flickering ON FAST TAPPINGS
                    // NOTE: This fixes possible flickering ON FAST TAPPINGS
                    // NOTE: This fixes possible flickering ON FAST TAPPINGS
                    self.layer.removeAllAnimations()
                    customAnim()
                }
        })

    }

}

如果你正在寻找灵活的动画,可以根据你的需要开始和停止,使用UIViewPropertyAnimator。

示例代码

let sampleView = UIView()

lazy var animator: UIViewPropertyAnimator = {
    let animator = UIViewPropertyAnimator(duration: 1.2, curve: .easeOut)
    animator.isInterruptible = true
    return animator
}()

// add and your animatable property
animator.addAnimations {
   // what you need to animate add here
   sampleView.alpha = 0
}

// start animation
animator.startAnimation(afterDelay: 0.5)

如果你需要在动画中间停下来。它将在当前状态下停止动画。

// stop animation
if animator.isRunning {
    animator.stopAnimation(true)
}