LoginSignup
0
0

コピペで! SwiftUI animation{} の使いかたとサンプル

Last updated at Posted at 2023-05-30

宣伝

アプリ作っているので入れてみてください!!
よろしくお願いいたします!!

本題

上記のコードでは、ボタンがタップされるとwithAnimationブロック内のアニメーションが実行されます。各ボタンに対応するアニメーションが異なり、円が左から右に移動します。

withAnimation(.easeInOut): イージング(徐々に速くなり、徐々に遅くなる)が適用されたアニメーションです。
withAnimation(.spring()): スプリングアニメーションが適用されたアニメーションです。バネのような振る舞いで、自然なバウンドが生じます。
withAnimation(.easeInOut(duration: 0.2)): 0.2秒の時間をかけてイージングアニメーションが実行されます。

それぞれのボタンをタップすると、円が異なるアニメーションで移動します。これにより、異なるアニメーション効果の違いを視覚的に確認することができます。

このサンプルコードをコピーして実行すると、異なるアニメーション効果が確認できるはずです。必要に応じてコードをカスタマイズして、さまざまなアニメーションを試してみてください。

struct ContentView: View {
    @State private var position: CGFloat = 0

    var body: some View {
        VStack {
            Spacer() // 上側の余白を追加

            Circle()
                .frame(width: 100, height: 100)
                .foregroundColor(.blue)
                .offset(x: position) // 指定した位置に円をオフセット

            Spacer() // 下側の余白を追加

            HStack(spacing: 20) {
                Button("easeInOut") {
                    withAnimation(.easeInOut) {
                        position += 100 // ボタンが押されるとアニメーションと共に位置を移動
                    }
                }

                Button("spring") {
                    withAnimation(.spring()) {
                        position += 100 // ボタンが押されるとスプリングアニメーションと共に位置を移動
                    }
                }

                Button("easeInOut(duration: 0.2)") {
                    withAnimation(.easeInOut(duration: 0.2)) {
                        position += 100 // ボタンが押されると指定された時間でアニメーションと共に位置を移動
                    }
                }
                Button("リセット") {
                    withAnimation {
                        position = 0 // リセットボタンが押されるとアニメーションと共に位置を初期値に戻す
                    }
                }
            }
        }
    }
}

宣伝

0
0
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
0
0