はじめに
この記事では、スワイプするとハンドスピナーの回転が加速するアニメーションを作る方法を紹介します。
対象者
SwiftUIの基本的な使い方を知っている人
やり方
struct ContentView: View {
@State private var angle: Double = 0
// 加速度
@State private var acceleration: Double = 0
private let timer = Timer.publish(every: 0.01, on: .main, in: .common).autoconnect()
var body: some View {
Image(systemName: "fanblades.fill")
.resizable()
.frame(width: 300, height: 300)
.rotationEffect(.degrees(angle))
.gesture(
DragGesture()
.onChanged { value in
// 加速度を更新
acceleration += value.translation.height / 10
}
)
.onReceive(timer) { _ in
// 減速させる
acceleration += -(acceleration * 0.01)
// 角度を更新
angle += acceleration
}
}
}
ポイント
-
DragGesture
を使って、スワイプした距離を加速度に反映させる -
Timer
を使って、0.01秒おきに角度の更新と減速を行う
おわりに
何年か前にハンドスピナーがすごく流行ったことがありましたね。この記事が参考になったという方は、フォローといいねしていただけると嬉しいです😆