Swift 實現無止盡 360 度旋轉動畫的三個方法
Published in
4 min readApr 24, 2020
開發 iOS App 時,我們有很多方法可以實現重覆 360 度旋轉的動畫。接下來我們分別看看以下三種實現的方法,SwiftUI 的 animation,UIKit 的 UIViewPropertyAnimator & UIKit 的 CABasicAnimation。
SwiftUI 的 animation
struct ContentView: View {
@State private var degrees: Double = 0
var body: some View {
VStack {
Image("peter")
.rotationEffect(.degrees(degrees))
.animation(Animation.linear(duration: 5).repeatForever(autoreverses: false))
Text("我因為你而轉\n一圈一圈自轉")
.font(.largeTitle)}
.onAppear {
self.degrees = 360
}
}
}
UIKit 的 UIViewPropertyAnimator
class RotateImageView: UIImageView {
func rotate() {
let animator = UIViewPropertyAnimator(duration: 5, curve: .linear) {[weak self] in
guard let self = self else { return }
self.transform = CGAffineTransform(rotationAngle: .pi)
}
animator.addAnimations {[weak self] in
guard let self = self else { return }
self.transform = self.transform.rotated(by: .pi)
}
animator.addCompletion {[weak self] (_) in
guard let self = self else { return }
self.rotate()
}
animator.startAnimation()
}
}
UIKit 的 CABasicAnimation
class RotateImageView: UIImageView {
func rotate() {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.toValue = Double.pi * 2
rotateAnimation.duration = 5
rotateAnimation.repeatCount = .infinity
layer.add(rotateAnimation, forKey: nil)
}
}
若想要畫面一出現就呼叫 rotate 開始動畫,記得要在 viewWillAppear 或 viewDidAppear 再加入 CABasicAnimation,在 viewDidLoad 加入的話動畫將失效。