首页 > 解决方案 > 视图唤醒时 UIView.animate() 冻结

问题描述

我用以下内容无限循环 UIView 动画

UIView.animate(withDuration: 1.0, delay: 0, options: [.autoreverse, .repeat], animations: {
        self.someLabel.alpha = 0.3
    }, completion: nil)

这很好用,但是当 viewController 唤醒时,动画会冻结在原来的位置。

运行与上面相同的代码viewDidWakeUp()并不能修复它。

如何使动画不冻结,或者在 viewController 唤醒时从中断处继续。

澄清一下,“醒来”是指以下任何一种:

标签: iosswiftuiviewanimation

解决方案


添加两个通知 willEnterForegroundNotification 和 didEnterBackgroundNotification。

这也值得注意。在某些情况下,您需要重置动画属性以使新动画保持不变。我可以通过动画转换来确认这一点。

只是打电话...

 view.layer.removeAllAnimations()
 self.someLabel.alpha = 1.0

//完整代码

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.

    NotificationCenter.default.addObserver(self, selector:#selector(didEnterForeground) , name: UIApplication.willEnterForegroundNotification, object: nil)

    NotificationCenter.default.addObserver(self, selector:#selector(didEnterBackground) , name: UIApplication.didEnterBackgroundNotification, object: nil)

}

@objc  func didEnterBackground() {
    view.layer.removeAllAnimations()
    self.someLabel.alpha = 1.0
}


@objc func didEnterForeground()  {

    DispatchQueue.main.async {
        self.animation()
    }

}
func animation() {

    UIView.animate(withDuration: 1.0, delay: 0, options: [.autoreverse, .repeat], animations: {
        self.someLabel.alpha = 0.3
    }, completion: nil)
}

推荐阅读