我想使用一個按鈕作爲切換 - 單擊一次&圖像無限旋轉。再次單擊,圖像停止,再次單擊,重新啓動。正確的方法來停止無限旋轉的圖像?以及如何實現removeAllAnimations?
我發現這個答案在獲得動畫繼續幫助: Rotate a view for 360 degrees indefinitely in Swift?
不過,我如何停止的事情不清楚。我已經實現了&以下的代碼,但它似乎有效,但我很好奇這是否是停止動畫的正確方法,或者是否有其他首選方法。此外 - 我的旋轉一直持續到完成,但我想知道是否可以在按下按鈕時凍結位置處的旋轉(我在下面的第二次嘗試中試過.removeAllAnimations(),但這似乎不起作用所有。
@IBOutlet weak var imageView: UIImageView!
var stopRotation = true
func rotateView(targetView: UIView, duration: Double = 1.0) {
if !stopRotation {
UIView.animate(withDuration: duration, delay: 0.0, options: .curveLinear, animations: {
targetView.transform = targetView.transform.rotated(by: CGFloat(Double.pi))
}) { finished in
self.rotateView(targetView: targetView, duration: duration)
}
}
}
@IBAction func spinPressed(_ sender: UIButton) {
stopRotation = !stopRotation
if !stopRotation {
rotateView(targetView: imageView)
}
}
這確實工作。我也想知道,如果它會是可能停止動畫中旬 - 旋轉。它的成立方式,動畫那張滿180度停止之前,我已經也嘗試在spinPressed操作中添加一個removeAnimation,並且在rotateView中刪除stopRotation檢查,但這似乎不起作用 - 旋轉繼續&只是在再次按下spinPressed時變得更快(參見下文):
@IBOutlet weak var imageView: UIImageView!
var stopRotation = true
func rotateView(targetView: UIView, duration: Double = 1.0) {
UIView.animate(withDuration: duration, delay: 0.0, options: .curveLinear, animations: {
targetView.transform = targetView.transform.rotated(by: CGFloat(Double.pi))
}) { finished in
self.rotateView(targetView: targetView, duration: duration)
}
}
@IBAction func spinPressed(_ sender: UIButton) {
stopRotation = !stopRotation
if stopRotation {
imageView.layer.removeAllAnimations()
} else {
rotateView(targetView: imageView)
}
}
確認第一種方法是否合理,這是值得歡迎的。如果有一種方法可以停止旋轉中間旋轉,那也是受歡迎的(也可以讓我直接思考我對removeAllAnimations的錯誤思考)。
謝謝! JG
也許檢查'finished'塊中'stopRotation'標誌的狀態?我使用的實現直接使用核心動畫,因此您可以通過提供給圖層的動畫關鍵字來控制動畫 – MadProgrammer