【问题标题】:UIView.animate() freezes when view wakes up视图唤醒时 UIView.animate() 冻结
【发布时间】:2019-11-02 07:55:27
【问题描述】:

我正在无限循环 UIView 动画,如下所示

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

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

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

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

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

  • 关闭应用并再次打开,此时 viewController 处于活动状态,
  • 让手机处于休眠状态,然后在此 viewController 仍处于活动状态的情况下唤醒它

【问题讨论】:

  • 你把你的动画放在哪里了?您是否尝试添加“viewDidAppear”?

标签: ios swift uiviewanimation


【解决方案1】:

添加两个通知 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)
}

【讨论】:

  • 非常感谢!对于其他有同样问题的人,我决定让我的“动画”方法为我重置。即 func animation(){ self.view.layer.removeAllAnimations() self.view.alpha = 1.0 UIView.animate(withDuration: 1.0, delay: 0, options: [.autoreverse, .repeat], animations: { self. someLabel.alpha = 0.3 },完成:无)}
猜你喜欢
  • 2018-09-13
  • 1970-01-01
  • 1970-01-01
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-16
相关资源
最近更新 更多