动画不停止使用 UIView.animate

Animation not stoping using UIView.animate

我的代码使用了一个简单的循环动画,它在 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()
    }

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

如果您需要更好地控制动画,您使用的动画方法是错误的。

改为使用 UIViewPropertyAnimator

备用 属性 动画器初始化器返回一个需要启动的动画器对象:

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

同样,您可以用于停止与动画师相关的动画

animator.stopAnimation()