UIView.animate with repeat 选项在新的 View Controller 出现时停止

Posted

技术标签:

【中文标题】UIView.animate with repeat 选项在新的 View Controller 出现时停止【英文标题】:UIView.animate with repeat option stops when new View Controller is presented 【发布时间】:2017-04-21 17:05:18 【问题描述】:

我有一个带有一个动画的视图控制器,该动画设置为使用options: [.autoreverse, .repeat] 无限循环 - 但是,当我呈现一个新的视图控制器(设置 VC)时,这很完美 - 然后将其关闭以返回视图动画,动画不是动画。视图 (ballContainer) 只是保持静态,而它应该仍然是动画。

animateBallViewIn 方法

func animateBallViewIn() 
    self.view.layoutIfNeeded()

    UIView.animate(withDuration: 0.5, animations: 
        self.ballContainer.alpha = 1.0
    )  (true) in

        UIView.animate(withDuration: 0.5, delay: 0.0, options: [.autoreverse, .repeat], animations: 
            ballViewBottomConstraint = 20.0

            self.view.layoutIfNeeded()
        , completion: nil)
    


注意 - 我在属性观察者中调用 animateBallViewIn()

如何让上述动画在从另一个视图控制器返回后保持动画?

【问题讨论】:

在 viewWillAppear 中调用这个函数! @Mannopson - viewDidAppear / viewWillAppear 中仍然存在问题 【参考方案1】:

如果视图消失或应用程序被最小化/最大化,动画将停止。这是预期的行为。

要解决这个问题,您应该评估 viewDidAppearapplicationDidBecomeActive 中对动画的需求,并在必要时调用您的 animateBallViewIn 方法。

【讨论】:

我现在正在检查是否需要动画,并在“viewDidAppear”中相应地调用 animateBallViewIn - 问题仍然存在。当我在点击设置屏幕后返回视图时,动画没有动画:(【参考方案2】:

您可以从视图中删除所有动画,然后使用 [.beginFromCurrentState] 选项重新启动动画。

【讨论】:

【参考方案3】:

解决该错误的方法: 设置一个计时器,每隔 0.3(示例时间)您的动画就会关闭,并完成“自动反转”它。不要在此处包含重复部分,因为每当计时器每 0.3 秒触发一次动作时,动画就会自动重复。

如果您仍然需要帮助,这可能会帮助您:

swift UIView animateWithDuration with repeat and autoreverse

【讨论】:

【参考方案4】:

在做重复约束动画时,除了触发viewWillAppear中的动画外,还必须将约束设置回viewWillDisappear中的起始位置。就我而言,它看起来像这样

override func viewWillDisappear(_ animated: Bool) 
    self.myConstraint.constant = 0

因为我有

self.myConstraint.constant = 20

在我的动画块中。

【讨论】:

以上是关于UIView.animate with repeat 选项在新的 View Controller 出现时停止的主要内容,如果未能解决你的问题,请参考以下文章

NSLayoutConstraint 不使用 UIView.animate 进行动画处理

UIView.animate 和完成问题

UIView.animate() 无法为视图设置动画的各种原因都有哪些?

视图框架的 UIView.animate 问题

动画没有停止使用 UIView.animate

对于在 UIView.animate 块内部或外部的循环?