繁体   English   中英

我如何继续旋转图像,直到服务器迅速做出响应

[英]How do i keep on rotating an image until a response from a server in swift

我现在每当单击一个按钮时都会进行异步调用,我希望像刷新图标一样的图像旋转或旋转,直到得到服务器的响应。 我现在只旋转180的pi,并且当响应到达时图像也不会重置。 在下面粘贴了我的示例代码:

//When the update button is clicked
@objc func updateHome(){
    UIView.animate(withDuration: 1) {
        self.updateIcon.transform = CGAffineTransform(rotationAngle: .pi)
    }
    getBalances()
}
//Inside getBalances function
DispatchQueue.main.async {
                        if responseCode == 0 {
                            let today = self.getTodayString()
                            print("Time: \(today)")
                            UIView.animate(withDuration: 1) {
                                self.updateIcon.transform = CGAffineTransform(rotationAngle: .pi)
                            }
}

这段代码使用CABasicAnimation无限期旋转UIImageView

let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(.pi * 2.0)
rotateAnimation.duration = 1.0  // Change this to change how many seconds a rotation takes
rotateAnimation.repeatCount = Float.greatestFiniteMagnitude

updateIcon.layer.add(rotateAnimation, forKey: "rotate")

当您从服务器收到信号时,您可以致电

updateIcon.layer.removeAnimation(forKey: "rotate")

停止动画

对于连续旋转,您也可以像下面一样使用CAKeyframeAnimation

@objc func updateHome() { 
        let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
        animation.duration = 1.0
        animation.fillMode = kCAFillModeForwards
        animation.repeatCount = .infinity
        animation.values = [0, Double.pi/2, Double.pi, Double.pi*3/2, Double.pi*2]
        let moments = [NSNumber(value: 0.0), NSNumber(value: 0.1),
                       NSNumber(value: 0.3), NSNumber(value: 0.8), NSNumber(value: 1.0)]
        animation.keyTimes = moments
        self.updateIcon.layer.add(animation, forKey: "rotate")
        getBalances()
    }

在您的Async方法(内部)DispatchQueue.main.async中,您可以像下面那样停止。 这将使您保持图像的原始位置。

self.updateIcon.layer.removeAllAnimations()

处理此问题的一种方法是添加一个实例变量来跟踪工作何时完成:

var finished: Bool = false

然后编写一个旋转图像的函数,并使用完成处理程序调用自身以继续旋转:

func rotateImage() {
    UIView.animate(withDuration: 1, 
    delay: 0.0,
    options: .curveLinear
    animations: {
        self.updateIcon.transform = CGAffineTransform(rotationAngle: .pi)
        },
    completion: { completed in
        if !self.finished {
          self.rotateImage()
        }
    }
    }
}

如果要立即停止动画,则应设置updateIcon.layer.removeAllAnimations() finished = true并调用updateIcon.layer.removeAllAnimations()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM