Communitygithub.com

SwiftUIアニメーション

iOS 13からiOS 26までの総合的なSwiftUIアニメーションリファレンス。VectorArithmeticプロトコル、@Animatableマクロ、スプリングとタイミングカーブの選択、アニメーションのデバッグを網羅。

SwiftUIアニメーション とは?

このスキルは、SwiftUIのアニメーションシステムに関する包括的なガイドです。アニメーションの基礎概念である補間(interpolation)とVectorArithmeticプロトコルから、iOS 26で導入された@Animatableマクロ、スプリングアニメーションとタイミングカーブアニメーションの比較、トランザクションシステムまでをカバーします。Animatableプロトコルへの準拠方法、カスタムアニメーションの実装、パフォーマンスの最適化、そして実世界のユースケース(フィンテック、ヘルスケア、ゲーム、生産性アプリ)での数値アニメーションの例を提供します。iOS 13、17、26それぞれのシステム要件に応じた機能を解説し、開発者がアニメーションの動作を理解し、効率的に実装できるよう支援します。

対応✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/IGTA-Tech/claude-skills-research/tree/HEAD/Axiom/.claude-plugin/plugins/axiom/skills/swiftui-animation-ref

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

SwiftUIアニメーション は何をしますか?

概要

SwiftUIのアニメーションシステムに関する包括的なガイド。基礎概念から高度なテクニックまでをカバーします。このスキルでは、Animatableプロトコル、iOS 26の@Animatableマクロ、アニメーションの種類、トランザクションシステムについて説明します。

核となる原則 SwiftUIのアニメーションは、VectorArithmeticプロトコルを基盤とした時間経過に伴う数学的な補間です。この基礎を理解することで、SwiftUIの宣言的アニメーションシステムの全機能を活用できます。

このスキルを使用するタイミング

  • カスタムアニメーションビューやシェイプの実装
  • プロパティがアニメーションしない理由の理解(Int vs Float/Double)
  • スプリングアニメーションとタイミングカーブアニメーションの選択
  • @Animatableマクロの使用(iOS 26以降)
  • ビューをAnimatableプロトコルに準拠させる
  • アニメーションのマージ動作のデバッグ
  • アニメーションパフォーマンスの最適化
  • 複数ステップや複雑なアニメーションの作成
  • モデル値と表示値の理解
  • カスタムアニメーションアルゴリズムの実装

システム要件

iOS 13以降:Animatableプロトコル

iOS 17以降:デフォルトスプリングアニメーション、スコープアニメーション

iOS 26以降:@Animatableマクロ


パート1:アニメーションの理解

補間とは

アニメーションとは、開始状態と終了状態の間の中間値を生成するプロセスです。

例:不透明度アニメーション

.opacity(0) → .opacity(1)

このアニメーションが実行されている間、SwiftUIは中間値を計算します:

0.0 → 0.02 → 0.05 → 0.1 → 0.25 → 0.4 → 0.6 → 0.8 → 1.0

値の分布方法

  • アニメーションのタイミングカーブまたは速度関数によって決定されます
  • スプリングアニメーションは物理シミュレーションを使用
  • タイミングカーブはベジェ曲線を使用
  • 各アニメーションタイプは異なる方法で値を計算

VectorArithmeticプロトコル

SwiftUIはアニメーションデータがVectorArithmeticに準拠することを要求します。これにより以下が提供されます:

protocol VectorArithmetic {
    // 2つの値の差を計算
    static func - (lhs: Self, rhs: Self) -> Self

    // 値のスケーリング
    static func * (lhs: Self, rhs: Double) -> Self

    // 値の加算
    static func + (lhs: Self, rhs: Self) -> Self

    // ゼロ値
    static var zero: Self { get }
}

組み込みの準拠型

  • 1次元: CGFloat, Double, Float, Angle
  • 2次元: CGPoint, CGSize
  • 4次元: CGRect

重要な洞察 ベクトル演算はアニメーションデータの次元を抽象化します。SwiftUIは単一の汎用実装ですべてのこれらの型をアニメーション化できます。

Intがアニメーションできない理由

IntはVectorArithmeticに準拠していません。その理由は:

  1. 分数の中間値がない — 3と4の間に「3.5」は存在しません
  2. 連続的ではない — 整数は離散値です
  3. スケーリングが意味をなさない — 整数に対して5 × 0.5は何を意味しますか?

試した場合の結果

struct CounterView: View {
    @State private var count: Int = 0

    var body: some View {
        Text("\(count)")
            .animation(.spring, value: count)
    }
}

結果: SwiftUIは単に古いテキストを新しいものに置き換えます。補間は発生しません。

解決策:FloatまたはDoubleを使用

struct AnimatedCounterView: View {
    @State private var count: Float = 0

    var body: some View {
        Text("\(Int(count))")
            .animation(.spring, value: count)
    }
}

結果: SwiftUIは0.0 → ... → 100.0を補間し、各フレームで丸めた整数を表示します。

モデル値と表示値

アニメーション可能な属性は、概念的には2つの値を持ちます:

モデル値

  • コードで設定された目標値
  • 状態が変更されたら即座に更新される
  • ビューのボディに記述する値

表示値

  • 現在レンダリングされている補間値
  • アニメーション中にフレームごとに更新される
  • ユーザーが実際に目にする値

例

.scaleEffect(selected ? 1.5 : 1.0)

selectedがtrueになったとき:

  • モデル値: 即座に1.5になる
  • 表示値: 時間とともに1.0 → 1.1 → 1.2 → 1.3 → 1.4 → 1.5と補間される

パート2:Animatableプロトコル

概要

Animatableプロトコルは、どのデータを補間すべきかを定義することで、ビューがそのプロパティをアニメーションできるようにします。

protocol Animatable {
    associatedtype AnimatableData: VectorArithmetic

    var animatableData: AnimatableData { get set }
}

SwiftUIは、このプロトコルに準拠する任意のビューに対してアニメーション可能な属性を構築します。

組み込みのAnimatableビュー

多くのSwiftUIモディファイアはAnimatableに準拠しています:

視覚効果

  • .scaleEffect() — スケール変換をアニメーション
  • .rotationEffect() — 回転をアニメーション
  • .offset() — 位置オフセットをアニメーション
  • .opacity() — 透明度をアニメーション
  • .blur() — ぼかし半径をアニメーション
  • .shadow() — 影のプロパティをアニメーション

すべてのシェイプ型

  • Circle, Rectangle, RoundedRectangle
  • Capsule, Ellipse, Path
  • カスタムShape実装

多次元データのためのAnimatablePair

複数のプロパティをアニメーションする場合、AnimatablePairを使用してベクトルを結合します。

例:scaleEffect実装

struct ScaleEffectModifier: ViewModifier, Animatable {
    var scale: CGSize
    var anchor: UnitPoint

    // 2つの2Dベクトルを1つの4Dベクトルに結合
    var animatableData: AnimatablePair<CGSize.AnimatableData, UnitPoint.AnimatableData> {
        get {
            AnimatablePair(scale.animatableData, anchor.animatableData)
        }
        set {
            scale.animatableData = newValue.first
            anchor.animatableData = newValue.second
        }
    }

    func body(content: Content) -> some View {
        content.scaleEffect(scale, anchor: anchor)
    }
}

仕組み

  • CGSizeは2次元(幅、高さ)
  • UnitPointは2次元(x、y)
  • AnimatablePairはこれらを4次元ベクトルに融合
  • SwiftUIは4つの値をすべて一緒に補間

カスタムAnimatable準拠

使用するタイミング

  • カスタムレイアウトのアニメーション(RadialLayoutなど)
  • カスタム描画コードのアニメーション
  • シェイプパスに影響するプロパティのアニメーション

例:アニメーションする数字ビュー

struct AnimatableNumberView: View, Animatable {
    var number: Double

    var animatableData: Double {
        get { number }
        set { number = newValue }
    }

    var body: some View {
        Text("\(Int(number))")
            .font(.largeTitle)
    }
}

// 使用法
AnimatableNumberView(number: value)
    .animation(.spring, value: value)

仕組み

  1. numberが0から100に変化
  2. SwiftUIはアニメーションのすべてのフレームでbodyを呼び出す
  3. 各フレームは新しいnumber値を受け取る:0 → 5 → 15 → 30 → 55 → 80 → 100
  4. テキストは補間された整数を表示するように更新される

パフォーマンスの警告

カスタムAnimatable準拠は高コストになる可能性があります。

ビューをAnimatableに準拠させると:

  • SwiftUIはアニメーションのすべてのフレームでビューのbodyを呼び出す
  • レイアウトがすべてのフレームで再実行される
  • これはメインスレッドで発生する

組み込みのアニメーション効果(.scaleEffect()、.opacity()など)ははるかに効率的です:

  • メインスレッド外で実行される
  • ビューのbodyを呼び出さない
  • レンダリングレイヤーのみを更新する

ガイドライン

  • 可能な限り組み込み効果を使用する
  • 組み込みモディファイアで効果を実現できない場合のみ、カスタムAnimatable準拠を使用する
  • パフォーマンス問題がある場合はInstrumentsでプロファイリングする

例:円形レイアウトアニメーション

// これは高コストですが、円形パスに沿ったアニメーションには必要です
@Animatable
struct RadialLayout: Layout {
    var offsetAngle: Angle

    var animatableData: Angle.AnimatableData {
        get { offsetAngle.animatableData }
        set { offsetAngle.animatableData = newValue }
    }

    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
        proposal.replacingUnspecifiedDimensions()
    }

    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
        let radius = min(bounds.width, bounds.height) / 2
        let center = CGPoint(x: bounds.midX, y: bounds.midY)
        let angleStep = Angle.degrees(360.0 / Double(subviews.count))

        for (index, subview) in subviews.enumerated() {
            let angle = offsetAngle + angleStep * Double(index)
            let x = center.x + radius * cos(angle.radians)
            let y = center.y + radius * sin(angle.radians)

            subview.place(at: CGPoint(x: x, y: y), anchor: .center, proposal: .unspecified)
        }
    }
}

なぜ必要なのか: offsetAngleをアニメーションするには、すべてのフレームで位置を再計算する必要があります。これを行う組み込みモディファイアはありません。


パート3:@Animatableマクロ(iOS 26以降)

概要

@Animatableマクロは、Animatableプロトコルに手動で準拠する際の定型的なコードを排除します。

iOS 26より前では、以下を行う必要がありました:

  1. Animatableに手動で準拠
  2. animatableDataのゲッターとセッターを記述
  3. 複数のプロパティにAnimatablePairを使用
  4. アニメーション不可のプロパティを手動で除外

iOS 26以降では、@Animatableを追加するだけです:

@MainActor
@Animatable
struct MyView: View {
    var scale: CGFloat
    var opacity: Double

    var body: some View {
        // ...
    }
}

マクロは自動的に:

  • Animatable準拠を生成
  • すべての格納プロパティを検査
  • VectorArithmeticに準拠したプロパティからanimatableDataを作成
  • 多次元データをAnimatablePairで処理

導入前後の比較

@Animatableマクロの前

struct HikingRouteShape: Shape {
    var startPoint: CGPoint
    var endPoint: CGPoint
    var elevation: Double
    var drawingDirection: Bool // これをアニメーションしたくない

    // 面倒な手動のanimatableData宣言
    var animatableData: AnimatablePair<AnimatablePair<CGFloat, CGFloat>,
                        AnimatablePair<Double, AnimatablePair<CGFloat, CGFloat>>> {
        get {
            AnimatablePair(
                AnimatablePair(startPoint.x, startPoint.y),
                AnimatablePair(elevation, AnimatablePair(endPoint.x, endPoint.y))
            )
        }
        set {
            startPoint = CGPoint(x: newValue.first.first, y: newValue.first.second)
            elevation = newValue.second.first
            endPoint = CGPoint(x: newValue.second.second.first, y: newValue.second.second.second)
        }
    }

    func path(in rect: CGRect) -> Path {
        // 描画コード
    }
}

@Animatableマクロの後

@Animatable
struct HikingRouteShape: Shape {
    var startPoint: CGPoint
    var endPoint: CGPoint
    var elevation: Double

    @AnimatableIgnored
    var drawingDirection: Bool // アニメーションから除外

    func path(in rect: CGRect) -> Path {
        // 描画コード
    }
}

コード行数: 20 → 12(40%削減)

@AnimatableIgnored

@AnimatableIgnoredを使用して、プロパティをアニメーションから除外します。

使用するタイミング

  • デバッグ値 — 開発専用のフラグ
  • ID — アニメーションすべきでない識別子
  • タイムスタンプ — ビューが作成/更新された時刻
  • 内部状態 — 視覚的でない内部管理用データ
  • 非VectorArithmetic型 — 色、文字列、ブール値

例

@MainActor
@Animatable
struct ProgressView: View {
    var progress: Double // アニメーションする
    var totalItems: Int // アニメーションする(Floatの場合。Intの場合はしない)

    @AnimatableIgnored
    var title: String // アニメーションしない

    @AnimatableIgnored
    var startTime: Date // アニメーションしない

    @AnimatableIgnored
    var debugEnabled: Bool // アニメーションしない

    var body: some View {
        VStack {
            Text(title)
            ProgressBar(value: progress)
            if debugEnabled {
                Text("開始: \(startTime.formatted())")
            }
        }
    }
}

実世界のユースケース

数値アニメーションは、アプリカテゴリ全体で非常に一般的です:

フィンテックアプリ

@MainActor
@Animatable
struct StockPriceView: View {
    var price: Double
    var changePercent: Double

    var body: some View {
        VStack(alignment: .trailing) {
            Text("$\(price, format: .number.precision(.fractionLength(2)))")
                .font(.title)
            Text("\(changePercent > 0 ? "+" : "")\(changePercent, format: .percent)")
                .foregroundColor(changePercent > 0 ? .green : .red)
        }
    }
}

ユースケース: 株価変動、ポートフォリオ価値、口座残高の遷移をアニメーション

ヘルス&フィットネス

@MainActor
@Animatable
struct HeartRateView: View {
    var bpm: Double

    @AnimatableIgnored
    var timestamp: Date

    var body: some View {
        VStack {
            Text("\(Int(bpm))")
                .font(.system(size: 60, weight: .bold))
            Text("BPM")
                .font(.caption)
                .foregroundColor(.secondary)
        }
    }
}

ユースケース: 心拍数インジケーター、歩数計、カロリー計算、移動距離

ゲーム

@MainActor
@Animatable
struct ScoreView: View {
    var score: Float
    var multiplier: Float

    var body: some View {
        HStack {
            Text("\(Int(score))")
                .font(.largeTitle)
            Text("×\(multiplier, format: .number.precision(.fractionLength(1)))")
                .font(.title2)
                .foregroundColor(.orange)
        }
    }
}

ユースケース: スコアアニメーション、XP遷移、レベル進行、コンボ乗数

生産性アプリ

@MainActor
@Animatable
struct TimerView: View {
    var remainingSeconds: Double


…

[翻訳のため省略]

Individual skills in this repo

This repo contains 7 individual skills — each has its own dedicated page.

IGTA-Tech/claude-skills-research

Use when localizing apps, using String Catalogs, generating type-safe symbols (Xcode 26+), handling plurals, RTL layouts, locale-aware formatting, or migrating from .strings files - comprehensive i18n patterns for Xcode 15-26

IGTA-Tech/claude-skills-research

Use when CAAnimation completion handler doesn't fire, spring physics look wrong on device, animation duration mismatches actual time, gesture + animation interaction causes jank, or timing differs between simulator and real hardware - systematic CAAnimation diagnosis with CATransaction patterns, frame rate awareness, and device-specific behavior

IGTA-Tech/claude-skills-research

This skill should be used when comparing two videos to analyze compression results or quality differences. Generates interactive HTML reports with quality metrics (PSNR, SSIM) and frame-by-frame visual comparisons. Triggers when users mention "compare videos", "video quality", "compression analysis", "before/after compression", or request quality assessment of compressed videos.

IGTA-Tech/claude-skills-research

Download YouTube videos and HLS streams (m3u8) from platforms like Mux, Vimeo, etc. using yt-dlp and ffmpeg. Use this skill when users request downloading videos, extracting audio, handling protected streams with authentication headers, or troubleshooting download issues like nsig extraction failures, 403 errors, or cookie extraction problems.

IGTA-Tech/claude-skills-research

Write high-converting landing page copy using proven frameworks like PAS (Problem-Agitate-Solution), AIDA, and StoryBrand. Creates headlines, value propositions, CTAs, and full page sections optimized for conversion. Use when users need landing page copy, sales page content, or marketing website text.

IGTA-Tech/claude-skills-research

Downloads videos from YouTube and other platforms for offline viewing, editing, or archival. Handles various formats and quality options.

IGTA-Tech/claude-skills-research

Download YouTube video transcripts when user provides a YouTube URL or asks to download/get/fetch a transcript from YouTube. Also use when user wants to transcribe or get captions/subtitles from a YouTube video.

関連スキル