iOS 在完成之前停止 animateWithDuration

标签 ios swift animatewithduration 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()
            }
        }
}

这是在自定义 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
    }
}

This answer may also be helpful.

关于iOS 在完成之前停止 animateWithDuration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36188349/

相关文章:

objective-c - 动画阿尔法变化

带按钮的 iPad UIPopoverController,与联系人应用程序相同

iOS Google Maps API - View 不会快速覆盖 map

ios - 如何在 Swift 中使用 UIWebView 管理 cookie

closures - animateWithDuration:animations:completion: 在 Swift 中

ios - 错误 - 无法使用类型为 'LineChartData' 的参数列表调用类型为 '(xVals: [String], dataSet: LineChartDataSet)' 的初始值设定项

ios - 用特定类型覆盖 UIViewController.view

ios - 如何在 iOS 中检测外接麦克风?

ios - 使用具有约束持续时间的动画快速移动按钮并在此期间检测触摸