我在 Swift 5 (Xcode 13.4.1) 中作業,我有 3 個影片應該在按下按鈕后運行。其中一個影片“旋轉”由函式定義。旋轉影片在持續時間結束后不會停止,它只是重新啟動。我正在嘗試使用self.UI_Image_Name.layer.removeAllAnimations.
我無法讓我的代碼等到影片完成才能運行該removeAllAnimations行。我一直在嘗試遵循本教程:等待任務完成
這是我當前的代碼:
@IBAction func flipButtonPress(_ sender: UIButton) {
// flipResult.image = results[Int.random(in: 0...1)]
self.animationGroup.enter()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now(), execute: { () -> Void in
//Slide coin image to middle of screen
UIView.animate(withDuration: 3, delay: 0,
options: [.curveEaseIn, .curveEaseOut],
animations: {
self.coinImage.frame.origin.y = 220
})
//Rotate Coin image
UIView.animate(withDuration: 11, delay: 3,
options: [.curveEaseIn, .curveEaseOut],
animations: {
self.coinImage.rotate()
})
//Fade away coin image
UIView.animate(withDuration: 5, delay: 6,
options: [],
animations: {
self.coinImage.alpha = 0.5
})
self.animationGroup.leave()
})
self.animationGroup.enter()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now(), execute: { () -> Void in
self.coinImage.layer.removeAllAnimations()
})
self.animationGroup.leave()
}
}
extension UIImageView{
func rotate() {
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.toValue = NSNumber(value: (Double.pi * 2) * 22)
rotation.duration = 11
rotation.isCumulative = true
rotation.repeatCount = Float.greatestFiniteMagnitude
rotation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
rotation.beginTime = CACurrentMediaTime() 3;
self.layer.add(rotation, forKey: "rotationAnimation")
}
}
uj5u.com熱心網友回復:
簡化選項
好的,這里有很多東西,其中之一,你可以洗掉影片組,好像它的唯一目的是在影片完成時幫助運行代碼,那么我們就不需要它了。
其次,影片帶有completion回呼。所以把你改成Fade away coin image這樣:
UIView.animate(withDuration: 5, delay: 6, options: []) {
self.coinImage.alpha = 0.5
} completion: { _ in
self.coinImage.layer.removeAllAnimations()
}
這意味著在 6 秒延遲和 5 秒影片之后,硬幣層影片將被移除
另外的選擇
如果這不能產生所需的效果,那么您可以嘗試這個(我個人盡量避免使用它,因為如果影片時間發生變化,它可能容易中斷):
DispatchQueue.main.asyncAfter(deadline: .now() <#Delay in seconds#>) {
<#code#>
}
這將在給定的秒數后運行閉包內的代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505320.html
上一篇:如何使計時器每10秒重置回0秒?
