2
3
paiza×Qiita記事投稿キャンペーン「プログラミング問題をやってみて書いたコードを投稿しよう!」

【SwiftUI】アニメーションとトランジションを組み合わせて連続して使う

Last updated at Posted at 2024-08-23

こんなカクカクのメッセージ的な表示。

sc 2024-08-23 at 11.20.52.gif

import SwiftUI

struct Message: View {
  var text: String

  @State private var showIcon = false
  @State private var showText = false

  var body: some View {
    HStack(spacing: 0) {
      if showIcon {
        Image(systemName: "heart.fill")
          .foregroundStyle(.red)
          .font(.title)
          .padding()
      }
      if showText {
        Text(text)
          .padding(.trailing, 24)
      }
    }
    .clipShape(.capsule)
    .background(
      .regularMaterial.shadow(.drop(radius: 16)),
      in: .capsule
    )
    .frame(height: 50)
    .onAppear {
      Task {
        showIcon = true
        try await Task.sleep(for: .seconds(1))
        showText = true
        try await Task.sleep(for: .seconds(1))
        showText = false
        try await Task.sleep(for: .seconds(1))
        showIcon = false
      }
    }
  }
}

private struct RefreshPreview: View {
  var text: String

  @State private var id = false

  var body: some View {
    Message(text: text)
      .id(id)

    Button("Refresh") {
      id.toggle()
    }
    .buttonStyle(.borderedProminent)
  }
}

#Preview {
  RefreshPreview(text: "Hello, world !!!")
    .padding()
    .frame(maxWidth: .infinity)
}

🤔 アニメーションとトランジションを組み合わせて使う

こんなに雰囲気変わるようです。

sc 2024-08-22 at 21.49.39.gif

これは、組み合わせて使ったほうがいいですね!

2
3
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
2
3