数学講師2862298 views
高校倫理1434987 views
高校生物550226 views
小学算数1196702 views
Computer365920 views
中学理科1627564 views
小学理科717868 views
高校化学2915516 views
教育149067 views
小学社会308942 views

SwiftUI Text のアニメーション

SwiftUI では Text の変化にアニメーションを付けられます。数値のカウントアップや、テキストの切り替えを滑らかに演出できます。

contentTransition

iOS 16 以降、.contentTransition() で Text の変化にトランジションを適用できます。

struct ContentView: View {
    @State private var count = 0
    
    var body: some View {
        VStack {
            Text("\(count)")
                .font(.largeTitle)
                .contentTransition(.numericText())
            
            Button("増やす") {
                withAnimation {
                    count += 1
                }
            }
        }
    }
}

.numericText() は数値の桁が変化するときに、数字がスライドするようなアニメーションを適用します。

numericText のオプション

カウントダウンかカウントアップかを指定できます。

Text("\(value)")
    .contentTransition(.numericText(countsDown: true))

interpolate トランジション

.interpolate は文字単位で滑らかに変化させます。

Text(isOn ? "ON" : "OFF")
    .contentTransition(.interpolate)

フォントや色のアニメーション

Text のスタイル変化もアニメーションできます。

struct ContentView: View {
    @State private var isHighlighted = false
    
    var body: some View {
        Text("タップしてね")
            .font(isHighlighted ? .title : .body)
            .foregroundStyle(isHighlighted ? .red : .primary)
            .animation(.easeInOut, value: isHighlighted)
            .onTapGesture {
                isHighlighted.toggle()
            }
    }
}

タイマーの自動アニメーション

Date を使ったタイマー表示は自動的に更新されます。

Text(Date(), style: .timer)
    .font(.largeTitle)
    .monospacedDigit()  // 数字の幅を固定してガタつき防止

monospacedDigit の重要性

数値が変化する Text では .monospacedDigit() を付けると、数字の幅が揃ってレイアウトが安定します。

Text("\(score)")
    .font(.title)
    .monospacedDigit()
    .contentTransition(.numericText())

Text のアニメーションを活用すると、数値や状態の変化をユーザーに分かりやすく伝えられます。