5
4

More than 1 year has passed since last update.

お題は不問!Qiita Engineer Festa 2023で記事投稿!

SwiftUIでハンドスピナーを作る方法

Posted at

はじめに

この記事では、スワイプするとハンドスピナーの回転が加速するアニメーションを作る方法を紹介します。

対象者

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秒おきに角度の更新と減速を行う

おわりに

何年か前にハンドスピナーがすごく流行ったことがありましたね。この記事が参考になったという方は、フォローといいねしていただけると嬉しいです😆

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4