iOS在完成之前停止animateWithDuration

raz*_*van 5 ios animatewithduration swift ios-animations

我有一个CollectionView,我想在用户选择的CollectionViewCell中创建一个动画.我选择使用animateKeyframesWithDuration,因为我想逐步创建自定义动画.我的代码看起来像这样:

func animate() {
    UIView.animateKeyframesWithDuration(1.0, delay: 0.0, options: .AllowUserInteraction, animations: { () -> Void in
        UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.5, animations: { () -> Void in
            //  First step
        })
        UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: { () -> Void in
            //  Second step
        })
        }) { (finished: Bool) -> Void in
            if self.shouldStopAnimating {
                self.loadingView.layer.removeAllAnimations()
            } else {
                self.animate()
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

选中此选项后,将在自定义CollectionViewCell内执行此操作.问题是我想强制在某个时刻立即停止动画.但是当我这样做时,动画并没有完全停止,它只是将剩下的动画移动到另一个单元格(可能是最后一个重用的单元格?)

我不明白为什么会这样.我尝试了不同的方法,但在正常进入完成块之前,它们都没有成功停止动画

有没有人对此有任何想法?

Cha*_*son 0

您可以尝试添加另一个持续时间很短的动画来设置要停止动画的视图属性,而不是从图层中删除动画。

像这样的东西:

if self.shouldStopAnimating {
    UIView.animate(withDuration: 0.01, delay: 0.0, options: UIView.AnimationOptions.beginFromCurrentState, animations: { () -> Void in
        //set any relevant properties on self.loadingView or anything else you're animating
        //you can either set them to the final animation values
        //or set them as they currently are to cancel the animation
    }) { (completed) -> Void in
    }
}
Run Code Online (Sandbox Code Playgroud)

这个答案也可能有帮助。