Communitygithub.com

ComeOnOliver/skillshub

在實作 SwiftUI 動畫、理解 VectorArithmetic、使用 @Animatable 巨集、縮放轉場、UIKit/AppKit 動畫橋接、在彈簧與時間曲線動畫之間選擇,或偵錯動畫行為時使用——涵蓋 iOS 13 到 iOS 26 的完整動畫參考。

skillshub 是什麼?

這份技能提供 SwiftUI 動畫系統的完整指南,從基礎概念到進階技術,涵蓋 iOS 13 至 iOS 26。它詳細說明 SwiftUI 動畫的數學基礎——VectorArithmetic 協定與插值原理,讓開發者理解模型值與演示值的區別。技能深入介紹 Animatable 協定的手動實作、自訂動畫資料處理,以及 iOS 26 才引進的 @Animatable 巨集,大幅簡化多維度動畫屬性的宣告。此外,它比較不同的動畫類型(時間曲線、彈簧動畫、高階動畫如延遲與重複),並解釋交易系統(withAnimation 與 .animation 修飾詞)的使用時機。技能也涵蓋 iOS 17 以上的範圍動畫、UIKit/AppKit 動畫橋接(iOS 18+)、縮放轉場與 CustomAnimation 協定等進階主題。這份技能支援 Cursor、Claude Code、Windsurf 等開發工具,其中也包含基於 SKILL.md 的全面動畫參考文件。

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

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

SwiftUI 動畫

概述

從基礎概念到進階技術,這份技能提供了 SwiftUI 動畫系統的完整指南。內容涵蓋 Animatable 協定、iOS 26 的 @Animatable 巨集、動畫類型以及交易系統。

核心原則 SwiftUI 中的動畫是基於數學插值的時間序列,由 VectorArithmetic 協定驅動。理解這個基礎,就能解鎖 SwiftUI 宣告式動畫系統的全部潛力。

系統需求

  • iOS 13+:Animatable 協定、時間/彈簧動畫
  • iOS 17+:預設彈簧動畫、範圍動畫、PhaseAnimator、KeyframeAnimator
  • iOS 18+:縮放轉場、UIKit/AppKit 動畫橋接
  • iOS 26+:@Animatable 巨集

第一部分:理解動畫

什麼是插值

動畫是在起始與結束狀態之間生成中間值的過程。

範例:透明度動畫

.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 能夠在任意兩個值之間進行插值。

內建符合的類型:CGFloat、Double、Float、Angle(一維)、CGPoint、CGSize(二維)、CGRect(四維)。

關鍵洞見:向量算術抽象了維度。SwiftUI 透過單一泛型實作來為所有這些類型執行動畫。

為什麼 Int 不能做動畫

Int 不符合 VectorArithmetic 協定——3 和 4 之間不存在分數中間值。SwiftUI 只會直接切換數值。

解決方案:使用 Float/Double,並以 Int 顯示:

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

模型值 vs 呈現值

可動畫的屬性在概念上有兩個值:

模型值

  • 由你的程式碼設定的目標值
  • 狀態改變時立即更新
  • 你在 view 的 body 中撰寫的值

呈現值

  • 目前正在渲染的插值
  • 在動畫過程中逐幀更新
  • 使用者實際看到的內容

範例

.scaleEffect(selected ? 1.5 : 1.0)

當 selected 變為 true 時:

  • 模型值:立即變成 1.5
  • 呈現值:隨著時間插值 1.0 → 1.1 → 1.2 → 1.3 → 1.4 → 1.5

第二部分:Animatable 協定

概述

Animatable 協定允許 view 透過定義哪些資料應該被插值來為其屬性執行動畫。

protocol Animatable {
    associatedtype AnimatableData: VectorArithmetic

    var animatableData: AnimatableData { get set }
}

SwiftUI 會為任何符合此協定的 view 建立一個可動畫的屬性。

內建的可動畫 View

許多 SwiftUI 修飾詞都符合 Animatable:

視覺效果

  • .scaleEffect() — 動畫縮放變形
  • .rotationEffect() — 動畫旋轉
  • .offset() — 動畫位置偏移
  • .opacity() — 動畫透明度
  • .blur() — 動畫模糊半徑
  • .shadow() — 動畫陰影屬性

所有 Shape 類型

  • Circle、Rectangle、RoundedRectangle
  • Capsule、Ellipse、Path
  • 自訂 Shape 實作

用於多維度資料的 AnimatablePair

當對多個屬性執行動畫時,使用 AnimatablePair 來組合向量。例如,scaleEffect 將 CGSize(二維)和 UnitPoint(二維)組合成一個四維向量:AnimatablePair<CGSize.AnimatableData, UnitPoint.AnimatableData>。透過 .first 和 .second 存取其組成部分。@Animatable 巨集(iOS 26+)完全消除了這種樣板程式碼。

自訂 Animatable 符合

何時使用

  • 為自訂佈局(如 RadialLayout)執行動畫
  • 為自訂繪圖程式碼執行動畫
  • 為影響形狀路徑的屬性執行動畫

範例:動畫數字 view

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 符合開銷很大——SwiftUI 在主執行緒上為每一幀呼叫 body。內建效果(.scaleEffect()、.opacity())在非主執行緒上執行,不會呼叫 body。僅在內建修飾詞無法達到效果時使用自訂符合(例如,為一個自訂 Layout 執行動畫,該佈局需要逐幀重新定位子 view)。


第三部分:@Animatable 巨集(iOS 26+)

概述

@Animatable 巨集消除了手動符合 Animatable 協定的樣板程式碼。

在 iOS 26 之前,你必須:

  1. 手動符合 Animatable
  2. 編寫 animatableData 的 getter 和 setter
  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 — 不應執行動畫的識別碼
  • 時間戳記 — view 的建立/更新時間
  • 內部狀態 — 非視覺的帳務紀錄
  • 非 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())")
            }
        }
    }
}

實際使用案例

@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: "價格")
    .animation(.spring(duration: 0.8), value: currentPrice)

第四部分:動畫類型

時間曲線動畫

時間曲線動畫使用貝茲曲線來控制動畫隨時間變化的速度。

內建預設值

.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 感覺更響應和精緻。


第五部分:交易系統

withAnimation

觸發動畫最常見的方式。

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

運作方式

  1. withAnimation 打開一個交易
  2. 在交易字典中設定動畫
  3. 執行閉包(狀態變更)
  4. 交易沿著 view 層級向下傳播
  5. 可動畫屬性檢查動畫並進行插值

顯式動畫

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

無動畫

withAnimation(nil) {
    // 變更立即發生,沒有動畫
    resetState()
}

animation() View 修飾詞

對 view 中的特定值套用動畫。

基本用法

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

運作方式:僅當 isActive 變更時才套用動畫。其他狀態變更不會觸發此動畫。

在同一個 view 上使用多個動畫

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 程式化)來套用不同的動畫。


第六部分:進階主題

CustomAnimation 協定

[內容已截斷進行翻譯]


第七部分:平台特定

UIKit/AppKit 動畫橋接(iOS 18+)

[內容已截斷進行翻譯]


第八部分:實用參考

速查表:何時使用何種動畫

[內容已截斷進行翻譯]

常見問題排解

[內容已截斷進行翻譯]


附錄

版本對照表

[內容已截斷進行翻譯]

延伸閱讀

[內容已截斷進行翻譯]

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

相關技能