Communitygithub.com

ComeOnOliver/skillshub

在实现 SwiftUI 动画、理解 VectorArithmetic、使用 @Animatable 宏、Zoom 过渡、UIKit/AppKit 动画桥接、在弹簧动画和时间曲线动画之间选择以及调试动画行为时使用——涵盖 iOS 13 到 iOS 26 的全面动画参考。

skillshub 是什么?

该技能提供了 SwiftUI 动画系统的全面指南,涵盖从 iOS 13 到 iOS 26 的基础概念和高级技术。核心原理是,SwiftUI 中的动画本质上是基于 VectorArithmetic 协议的数学插值过程。它详细解释了 Animatable 协议、iOS 26 中新增的 @Animatable 宏(可以大幅减少样板代码)以及事务系统。技能还包括各种动画类型(包括弹簧动画和时间曲线动画)、高级主题(如 Zoom 过渡和 UIKit/AppKit 桥接)以及性能优化建议。无论你是实现简单动画还是复杂的自定义布局,本技能都能为你提供全面的示例和最佳实践。

兼容平台~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+:Zoom 过渡、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 能够在任意两个值之间进行插值。

内置遵循类型: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)

模型值与呈现值

可动画属性在概念上有两个值:

模型值

  • 你的代码设置的目标值
  • 状态变化时立即更新
  • 你在视图 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 为任何遵循此协议的视图构建一个可动画属性。

内置可动画视图

许多 SwiftUI 修饰符遵循 Animatable:

视觉效果

  • .scaleEffect() — 动画缩放变换
  • .rotationEffect() — 动画旋转
  • .offset() — 动画位置偏移
  • .opacity() — 动画透明度
  • .blur() — 动画模糊半径
  • .shadow() — 动画阴影属性

所有形状类型

  • 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. 文本更新以显示插值后的整数

性能警告

自定义 Animatable 遵循代价高昂——SwiftUI 在主线程上为每一帧调用 body。内置效果(.scaleEffect()、.opacity())在主线程之外运行,不会调用 body。仅在无法通过内置修饰符实现效果时才使用自定义遵循(例如,动画逐帧重新定位子视图的自定义 Layout)。


第 3 部分:@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 — 不应动画的标识符
  • 时间戳 — 视图创建/更新时间
  • 内部状态 — 非可视记账
  • 非 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: "价格")
    .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 协议

...(此处原文已截断,翻译将保留原样)

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

相关技能