Communitygithub.com

ComeOnOliver/skillshub

SwiftUIアニメーションの実装、VectorArithmeticの理解、@Animatableマクロの使用、ズーム遷移、UIKit/AppKitアニメーションブリッジ、スプリングとタイミングカーブアニメーションの選択、アニメーション動作のデバッグに使用します。iOS 13からiOS 26までを網羅した包括的なアニメーションリファレンスです。

skillshub とは?

このスキルは、SwiftUIのアニメーションシステムに関する包括的なガイドです。iOS 13からiOS 26までのすべての主要なアニメーション機能をカバーしており、基本概念から高度なテクニックまでを詳細に説明します。具体的には、VectorArithmeticプロトコルに基づく数学的補間の原理、Animatableプロトコルによるカスタムアニメーション、iOS 26で導入された@Animatableマクロによるボイラープレートコードの削減、スプリングアニメーションとタイミングカーブアニメーションの違いと使い分け、トランザクションシステム(withAnimation、animation()修飾子、スコープ付きアニメーション)、そしてCustomAnimationプロトコルやキーフレームアニメーターなどの高度なトピックを解説します。開発者はこのスキルを参照することで、SwiftUIアニメーションの基礎を理解し、複雑なアニメーション効果を実装し、アニメーションのパフォーマンスを最適化できるようになります。これは、Claude CodeやCursor、CodexなどのAIエージェントがSwiftUIアニメーション関連のコードを生成・デバッグする際の信頼できる知識ソースとして機能します。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/CharlesWiltgen/Axiom/axiom-swiftui-animation-ref

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

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

ドキュメント

SwiftUI アニメーション

概要

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

核心的な原則 SwiftUIにおけるアニメーションとは、時間経過に伴う数学的な補間であり、VectorArithmeticプロトコルによって支えられています。この原則を理解することで、SwiftUIの宣言型アニメーションシステムの真の力を引き出すことができます。

システム要件

  • iOS 13以上: Animatableプロトコル、タイミング/スプリングアニメーション
  • iOS 17以上: デフォルトのスプリングアニメーション、スコープ付きアニメーション、PhaseAnimator、KeyframeAnimator
  • iOS 18以上: ズーム遷移、UIKit/AppKitアニメーションブリッジ
  • 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に準拠していることを要求します。これにより、減算、スケーリング、加算、およびゼロ値が提供され、SwiftUIは任意の2つの値の間を補間できます。

組み込みの準拠型: CGFloat、Double、Float、Angle (1D)、CGPoint、CGSize (2D)、CGRect (4D)。

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

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

IntはVectorArithmeticに準拠していません。3と4の間には分数の中間値が存在しません。SwiftUIは単純に値をスナップします。

解決策: Float/Doubleを使用し、Intとして表示します:

@State private var count: Float = 0
// ...
Text("\(Int(count))")
    .animation(.spring, value: count)

モデル値とプレゼンテーション値

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

モデル値

  • コードによって設定される目標値
  • 状態が変化するとすぐに更新される
  • ビューのbodyに記述する値

プレゼンテーション値

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

例

.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() — シャドウプロパティをアニメーション化

すべてのShape型

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

多次元データのためのAnimatablePair

複数のプロパティをアニメーション化する場合は、AnimatablePairを使用してベクトルを結合します。例えば、scaleEffectはCGSize (2D) とUnitPoint (2D) を、AnimatablePair<CGSize.AnimatableData, UnitPoint.AnimatableData>を介して4Dベクトルに結合します。コンポーネントには.firstと.secondでアクセスします。@Animatableマクロ (iOS 26以上) を使用すると、このボイラープレートが完全に不要になります。

カスタム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. Textが更新され、補間された整数が表示される

パフォーマンスに関する警告

カスタムAnimatable準拠は高コストです — SwiftUIはすべてのフレームでメインスレッド上でbodyを呼び出します。組み込み効果 (.scaleEffect()、.opacity()) はメインスレッド外で実行され、bodyを呼び出しません。組み込みモディファイアで効果を実現できない場合(例: フレームごとにサブビューを再配置するカスタムLayoutのアニメーション化)にのみ、カスタム準拠を使用してください。


パート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("Started: \(startTime.formatted())")
            }
        }
    }
}

実世界での使用例

@Animatableは、株価、心拍数、スコア、タイマー、プログレスバーなど、あらゆる数値表示に有効です:

@MainActor
@Animatable
struct AnimatedValueView: View {
    var value: Double
    var changePercent: Double

    @AnimatableIgnored
    var label: String

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

// 使用法
AnimatedValueView(value: currentPrice, changePercent: 0.025, label: "Price")
    .animation(.spring(duration: 0.8), value: currentPrice)

パート4: アニメーションの種類

タイミングカーブアニメーション

タイミングカーブアニメーションは、ベジェ曲線を使用して、時間の経過に伴うアニメーションの速度を制御します。

組み込みのプリセット

.animation(.linear)          // 一定速度
.animation(.easeIn)          // ゆっくり開始、速く終了
.animation(.easeOut)         // 速く開始、ゆっくり終了
.animation(.easeInOut)       // 開始と終了はゆっくり、中間は速い

カスタムタイミングカーブ

let customCurve = UnitCurve(
    startControlPoint: CGPoint(x: 0.2, y: 0),
    endControlPoint: CGPoint(x: 0.8, y: 1)
)

.animation(.timingCurve(customCurve, duration: 0.5))

持続時間

すべてのタイミングカーブアニメーションは、オプションの持続時間を受け入れます:

.animation(.easeInOut(duration: 0.3))
.animation(.linear(duration: 1.0))

デフォルト: 0.35秒

スプリングアニメーション

スプリングアニメーションは物理シミュレーションを使用して、自然で有機的な動きを作り出します。

組み込みのプリセット

.animation(.smooth)     // バウンスなし (iOS 17以降のデフォルト)
.animation(.snappy)     // 少量のバウンス
.animation(.bouncy)     // 多めのバウンス

カスタムスプリング

.animation(.spring(duration: 0.6, bounce: 0.3))

パラメータ

  • duration — 知覚されるアニメーションの持続時間
  • bounce — バウンスの量 (0 = バウンスなし、1 = 非常にバウンスが多い)

従来のスプリングパラメータ (質量、剛性、減衰) よりもはるかに直感的です。

高次アニメーション

基本アニメーションを変更して、複雑なエフェクトを作成します。

遅延

.animation(.spring.delay(0.5))

アニメーションを開始する前に0.5秒待機します。

繰り返し

.animation(.easeInOut.repeatCount(3, autoreverses: true))
.animation(.linear.repeatForever(autoreverses: false))

アニメーションを複数回または無限に繰り返します。

速度

.animation(.spring.speed(2.0))  // 2倍の速さ
.animation(.spring.speed(0.5))  // 2倍の遅さ

アニメーションの速度を乗算します。

デフォルトアニメーションの変更 (iOS 17以上)

iOS 17以前

withAnimation {
    // デフォルトでタイミングカーブを使用
}

iOS 17以上

withAnimation {
    // デフォルトで.smoothスプリングを使用
}

変更理由: スプリングアニメーションはより自然に感じられ、中断された場合に速度を保持します。

推奨: スプリングを採用しましょう。UIの応答性と洗練度が向上します。


パート5: トランザクションシステム

withAnimation

アニメーションをトリガーする最も一般的な方法です。

Button("拡大") {
    withAnimation(.spring) {
        scale = 1.5
    }
}

仕組み

  1. withAnimationがトランザクションを開く
  2. トランザクションディクショナリにアニメーションを設定する
  3. クロージャを実行する (状態変更)
  4. トランザクションがビュー階層を伝播する
  5. アニメーション可能な属性がアニメーションをチェックし、補間する

明示的なアニメーション

withAnimation(.spring(duration: 0.6, bounce: 0.4)) {
    isExpanded.toggle()
}

アニメーションなし

withAnimation(nil) {
    // 変更は即座に発生し、アニメーションなし
    resetState()
}

animation() ビューモディファイア

ビュー内の特定の値にアニメーションを適用します。

基本的な使用法

Circle()
    .fill(isActive ? .blue : .gray)
    .animation(.spring, value: isActive)

仕組み: アニメーションはisActiveが変更された場合にのみ適用されます。他の状態変更ではこのアニメーションはトリガーされません。

同じビューに対する複数のアニメーション

Circle()
    .scaleEffect(scale)
    .animation(.bouncy, value: scale)
    .opacity(opacity)
    .animation(.easeInOut, value: opacity)

プロパティごとに異なるアニメーション。

スコープ付きアニメーション (iOS 17以上)

アニメーションを特定のアニメーション可能な属性に狭くスコープします。

従来のアプローチの問題

struct AvatarView: View {
    var selected: Bool

    var body: some View {
        Image("avatar")
            .scaleEffect(selected ? 1.5 : 1.0)
            .animation(.spring, value: selected)
            // ⚠️ selectedが変更されたときに画像も変更される場合、
            //    画像のトランジションもアニメーション化される (意図せず)
    }
}

解決策: スコープ付きアニメーション

struct AvatarView: View {
    var selected: Bool

    var body: some View {
        Image("avatar")
            .animation(.spring, value: selected) {
                $0.scaleEffect(selected ? 1.5 : 1.0)
            }
            // ✅ scaleEffectのみがアニメーション化され、画像のトランジションはアニメーション化されない
    }
}

仕組み

  • アニメーションはクロージャ内の属性にのみ適用される
  • 他の属性は影響を受けない
  • 偶発的なアニメーションを防ぐ

カスタムトランザクションキー

カスタムのTransactionKey型を定義して、トランザクションシステムを通じてコンテキストを伝播します。withTransactionを使用して値を設定し、.transactionモディファイアを使用して値を読み取ります。これにより、状態変更がどのようにトリガーされたか (タップ vs プログラム) に基づいて、異なるアニメーションを適用できます。


パート6: 高度なトピック

CustomAnimation プロトコル

Imp

…

[翻訳のため省略]

Individual skills in this repo

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

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

関連スキル