[英]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.