😊

【SwiftUI】アニメーションの書き方

2024/08/16に公開

基本として。

import SwiftUI

struct TextAnimationView: View {
  @State private var scale = false
  @State private var rotation = false
  @State private var opacity = false
  @State private var offset = false

  var body: some View {
    VStack {
      Image(systemName: "face.smiling")
        .font(.system(size: 100))

        .scaleEffect(scale ? 2 : 1)
        .animation(.default, value: scale)

        .rotationEffect(.degrees(rotation ? 0 : 360))
        .animation(.easeIn, value: rotation)
      
        .opacity(opacity ? 0.2 : 1)
        .animation(.easeOut, value: opacity)

        .offset(CGSize(width: offset ? 50 : 0, height: offset ? 50 : 0))
        .animation(.spring(duration: 0.5, bounce: 0.5), value: offset)

      Button("scale") {
        scale.toggle()
      }
      Button("rotation") {
        rotation.toggle()
      }
      Button("opacity") {
        opacity.toggle()
      }
      Button("offset") {
        offset.toggle()
      }
    }
    .buttonStyle(.borderedProminent)
  }
}

#Preview {
  TextAnimationView()
    .padding()
}

withAnimation() より animation() のほうが View につくのでわかりやすくない?

https://android.benigumo.com/20240422/withanimation-animation/

https://zenn.dev/maochanz/articles/0bcd4bfaa43a0d

アニメーションとトランジションを組み合わせて使うと画面が生き生きします。

https://android.benigumo.com/20240822/swiftui-animation-transition/

https://x.com/maochanz/status/1827873597471199498

https://android.benigumo.com/20240827/speech-bubble/

Discussion