简体   繁体   English

视图唤醒时 UIView.animate() 冻结

[英]UIView.animate() freezes when view wakes up

I'm infinitely looping a UIView animation with the following我无限循环 UIView animation 与以下

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

This works fine but when the viewController wakes up the animation freezes where it is.这工作正常,但是当 viewController 唤醒时 animation 冻结在它所在的位置。

Running the same code as above in viewDidWakeUp() doesn't fix it.viewDidWakeUp()中运行与上面相同的代码并不能修复它。

How can I make the animation either not freeze, or continue where it left off when the viewController wakes up.如何使 animation 不冻结,或者在 viewController 唤醒时从中断处继续。

To clarify, by 'wake up' I mean either of the following:澄清一下,“醒来”是指以下任何一种:

  • Closing the app and opening it again, with this viewController active,关闭应用程序并再次打开它,此 viewController 处于活动状态,
  • Sleeping the phone and then waking it with this viewController still active让手机休眠,然后用这个 viewController 唤醒它仍然处于活动状态

Add two notification willEnterForegroundNotification and didEnterBackgroundNotification.添加两个通知 willEnterForegroundNotification 和 didEnterBackgroundNotification。

It is also worth noting.这也值得注意。 That in some cases, you need to reset the animated property to get the new animation to stick.在某些情况下,您需要重置动画属性以使新的 animation 保持不变。 I can confirm this with an animated transformation.我可以通过动画转换来确认这一点。

Just calling...只是打电话...

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

//Complete code //完整代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM