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

时间:2018-10-15 18:31:45

标签: ios swift uiview

我现在每当单击一个按钮时都会进行异步调用,我希望像刷新图标一样的图像旋转或旋转,直到得到服务器的响应。我现在只旋转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)
                            }
}

3 个答案:

答案 0 :(得分:0)

此代码使用File fullPath = new File(path); File directory = new File(fullPath.getParent()); directory.mkdirs(); File file = new File(directory, fullPath.getName()); 无限期旋转UIImageView

CABasicAnimation

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

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

停止动画

答案 1 :(得分:0)

要进行连续旋转,您也可以像下面一样使用 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()

答案 2 :(得分:0)

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

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

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