【问题标题】:Animation not stoping using UIView.animate动画没有停止使用 UIView.animate
【发布时间】:2019-07-21 21:31:28
【问题描述】:

我的代码使用了一个简单的循环动画,该动画在 5 秒后不会停止。我想要做的就是有一个停止动画的第二个按钮。正如您在我的代码中看到的那样,circle.stopAnimating() 无效。

class VET: UIViewController {
    @IBOutlet weak var circle: UIImageView!
    var duration = 5

    @IBAction func start(_ sender: Any) {
        UIView.animate(withDuration: TimeInterval(duration), delay: 0.5, options: [.repeat, .autoreverse, .curveEaseIn, .curveEaseOut], animations: { () -> Void in
            let scale = CGAffineTransform(scaleX: 0.25, y: 0.25)
            self.circle.transform = scale
            print("animation")
        }, completion: { _ in
            //if finished { or (finished: Bool)
            // if isAnimating {
            if self.circle.isAnimating {
                self.circle.stopAnimating()
                print("is animating -- stop animating")
            } else {
                self.circle.startAnimating()
                print("start animating")
            }
        })
    }

    @IBAction func stop() {
        circle.stopAnimating()
    }

【问题讨论】:

  • 1. UIImage start/stopAnimating()UIView.animate 无关。如果您设置图像视图的animationImages 属性,它们正在使用。 2. UIView.animate 完成块在动画完成之前不会被调用(在这种情况下是 5.5 秒后)。
  • 即使经过 5.5 秒也没有任何反应。
  • 这个动画无限循环。
  • 再次阅读我的第一点。
  • 了解如何设置图像视图属性。如果我只想将动画设置为运行 10 秒并停止我将在属性中写入的内容。

标签: ios swift uiimageview uiviewanimation completion


【解决方案1】:

startAnimating 和 stopAnimating 用于在 GIF 等间隔内更改 imageview 的图像。在这里,您使用了带有重复的动画块,并且仅在动画中断时才会调用完成块。例如,当应用程序进入后台并再次返回前台时,它会被调用。

要在某个时间间隔后停止动画,您必须在该时间间隔后强制调用 removeAllAnimations。请参考以下代码:

@IBOutlet weak var circle: UIImageView!
var duration = 10

func start() {
    UIView.animate(withDuration: TimeInterval(duration), delay: 0.5, options: [.repeat, .autoreverse, .curveEaseIn, .curveEaseOut], animations: { () -> Void in
        let scale = CGAffineTransform(scaleX: 0.25, y: 0.25)
        self.circle.transform = scale
        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(self.duration * 1000)) {
            // Code
            self.circle.layer.removeAllAnimations()
        }

        print("animation")
    }, completion: { _ in

        let scale = CGAffineTransform(scaleX: 1.0, y: 1.0)
        self.circle.transform = scale
    })
}

【讨论】:

    【解决方案2】:

    如果您需要对动画进行更多控制,那么您使用动画的方法是错误的。

    改为使用 UIViewPropertyAnimator

    备用属性 animator 初始化程序会返回一个需要启动的 animator 对象:

    let animator = UIViewPropertyAnimator(duration: duration, curve: .linear) {
        self.redSquare.backgroundColor = .green
    }
    animator.startAnimation()
    

    同样你可以用来停止与动画师相关的动画

    animator.stopAnimation()
    

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多