Swift UIViewPropertyAnimator 在离开应用程序时自动播放

Swift UIViewPropertyAnimator automatically plays when leaving app

大家好!

我的应用程序有问题。我正在使用 UIViewPropertyAnimator 为我的模糊设置动画。我让模糊效果 运行 从 nil (0) 到 .light (1),但是因为光效太多了,我将 UIViewPropertyAnimator 设置为 0.1 (.fractioncomplete = 0.1)。

这太棒了!但问题是,如果你离开应用程序(不是杀死,只是通过按主页按钮离开或转到另一个应用程序),它会自动播放并从 0.1 变为 1。

我认为这是一个错误?我希望有人对此有解决方案。

这里有一些图片:(声望不够直接post)

picture with blur on 0.1

picture with blur on 1

代码:

let effectView = UIVisualEffectView(effect: nil)
var animator: UIViewPropertyAnimator?

viewdidload:

effectView.frame = view.bounds
effectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mainView.addSubview(effectView)
animator = UIViewPropertyAnimator(duration: 1, curve: .linear) {
   self.effectView.effect = UIBlurEffect(style: .light)
}

模糊动作(需要先start/pause,因为苹果有一个已知的错误来唤醒动画师):

self.animator?.startAnimation()
self.animator?.pauseAnimation()
self.animator?.fractionComplete = CGFloat(0.1)

提前致谢!

我重现了你的问题,并确认了这个行为,但我怀疑这是一个错误。 属性 动画师刚刚 returns 从暂停状态变为活动状态并运行动画。要克服它,您必须 stop 它然后 finish 当前 部分状态(各个状态在 docs 中描述)。这里还有一个问题 - 在设置 fractionComplete 后以某种方式将其停止在 0,因此您必须等待一段时间(非常短)。在您的 "blurAction":

下尝试此代码
    self.animator?.startAnimation()
    self.animator?.pauseAnimation()
    self.animator?.fractionComplete = CGFloat(0.1)

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { 
        self.animator?.pauseAnimation()
        self.animator?.stopAnimation(true)
        self.animator?.finishAnimation(at: .current)
    }

我验证它适用于 background/foreground 应用程序生命周期更改。

我通过在设置 fractionComplete 后立即将 UIViewPropertyAnimatorpausesOnCompletion 属性 设置为 true 解决了这个问题。无需重启动画器。