我有一个 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()
}
}
}
这是在自定义 CollectionViewCell 被选中时在其内部执行的。 问题是我想在某个特定点立即强制停止动画。但是当我这样做时,动画并没有完全停止,它只是将剩余的动画移动到不同的单元格(可能是最后一个重复使用的单元格?)
我不明白为什么会这样。我尝试了不同的方法,但在正常进入完成 block 之前,它们都没有成功停止动画
有人知道吗?
最佳答案
您可以尝试添加另一个持续时间非常短的动画,而不是从图层中删除动画,以设置您想要停止动画的 View 属性。
像这样:
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
}
}
关于iOS 在完成之前停止 animateWithDuration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36188349/