iOS在完成前停止动画持续时间

iOS在完成前停止动画持续时间,ios,swift,animatewithduration,ios-animations,Ios,Swift,Animatewithduration,Ios Animations,我有一个CollectionView,我想在用户选择的CollectionViewCell内创建一个动画。我选择使用animateKeyframesWithDuration,因为我想一步一步地创建自定义动画。我的代码如下所示: func animate() { UIView.animateKeyframesWithDuration(1.0, delay: 0.0, options: .AllowUserInteraction, animations: { () -> Void in

我有一个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()
            }
        }
}
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
    }
}
选中此选项后,将在自定义CollectionViewCell内执行。 问题是我想在某个特定点强制立即停止动画。但当我这样做时,动画并没有完全停止,它只是将剩余的动画移动到另一个单元上(可能是最后一个重用的单元?)

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


有人知道这一点吗?

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

大概是这样的:

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()
            }
        }
}
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
    }
}

它仍然不起作用。在我选定的单元格上,动画将正常停止。真正的问题是它在另一个细胞上继续。我也尝试过UIView.SetAnimationEnabled(false),但没有成功。这真的很烦人你找到解决办法了吗?