首页 > 解决方案 > 如何停止动画并立即开始新动画?

问题描述

我有这种情况,按下连接按钮,并连续动画直到 VPN 连接。然后我想停止动画并加载一组新的图像并只动画一次。

@IBOutlet weak var vpnButton: UIImageView!
var premiumImages: [UIImage] = []
var loadingImages: [UIImage] = []


@objc private func vpnStatusDidChange(_ notification: Notification) {
        let nevpnconn = notification.object as! NEVPNConnection
        let status = nevpnconn.status
        switch status {
        case NEVPNStatus.connecting:
            self.animateImages(imageView: self.vpnButton, images: loadingImages, duration: 1.0, isInfinite: true)
            self.vpnButton.image = UIImage(named: "Red-1")
}

处理动画的方法:

func animateImages(imageView: UIImageView, images: [UIImage], duration: Double, isInfinite: Bool=false) {
        imageView.stopAnimating()
        imageView.animationImages = images
        imageView.animationDuration = duration
        if !isInfinite {
            imageView.animationRepeatCount = 1
        } else {
            imageView.animationRepeatCount = 0
        }
        imageView.startAnimating()
    }

因此,每当我调用它时,它都会停止任何现有的动画并使用新图像对其进行动画处理。

一旦 VPN 连接成功:

case NEVPNStatus.connected:
     self.vpnButton.highlightedImage = UIImage(named: "OrangePressed")
     self.animateImages(imageView: self.vpnButton, images: premiumImages, duration: 0.25)
     self.vpnButton.image = UIImage(named: "OrangePremium-3")

只有loadingImages得到正确的动画。第二组premiumImages没有动画,只显示最后一帧。

我怀疑 stopAnimating() 需要一些时间才能完成,理想情况下,我需要一个完成处理程序来知道何时启动imageView.startAnimating().

标签: iosswiftanimation

解决方案


推荐阅读