LaTeX957300 views
いろは2986023 views
中学英語808712 views
高校化学2913383 views
りんご192546 views
高校物理158224 views
ヒストリア284143 views
Computer365120 views
高校倫理1433119 views
小学社会308636 views
Help
Tools

English

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 のアニメーションを活用すると、数値や状態の変化をユーザーに分かりやすく伝えられます。