Communitygithub.com

SwiftUI 动画

用于实现 SwiftUI 动画、理解 VectorArithmetic、使用 @Animatable 宏、在弹簧动画和时间曲线动画之间进行选择,或调试动画行为时使用——涵盖从 iOS 13 到 iOS 26 的全面动画参考。

SwiftUI 动画 是什么?

该技能提供了 SwiftUI 动画系统的全面指南,涵盖从 iOS 13 到 iOS 26 的核心概念和高级技术。它解释了动画的本质是基于 VectorArithmetic 协议的数学插值,并深入讲解了 Int 无法动画的原因以及使用 Float/Double 的解决方案。技能详细介绍了 Animatable 协议的手动实现方式,以及在 iOS 26+ 中通过 @Animatable 宏自动生成动画数据,大幅减少样板代码。此外,它还包括了动画类型(弹簧动画和时间曲线动画)、事务系统的原理,以及如何优化自定义动画性能的最佳实践,是任何 SwiftUI 开发者必备的参考。

兼容平台✓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 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

SwiftUI 动画 是做什么的?

概述

SwiftUI 动画系统的全面指南,从基础概念到高级技术。本技能涵盖 Animatable 协议、iOS 26 的 @Animatable 宏、动画类型以及事务系统。

核心原则 SwiftUI 中的动画是随时间进行的数学插值,由 VectorArithmetic 协议驱动。理解这一基础将解锁 SwiftUI 声明式动画系统的全部潜力。

何时使用此技能

  • 实现自定义动画视图或形状
  • 理解为什么某个属性不能动画(Int 与 Float/Double)
  • 在弹簧动画和时间曲线动画之间进行选择
  • 使用 @Animatable 宏(iOS 26+)
  • 使视图符合 Animatable 协议
  • 调试动画合并行为
  • 优化动画性能
  • 创建多步骤或复杂动画
  • 理解模型值与表现值
  • 实现自定义动画算法

系统要求

iOS 13+ 支持 Animatable 协议

iOS 17+ 支持默认弹簧动画、作用域动画

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,它提供了:

protocol VectorArithmetic {
    // 计算两个值之间的差值
    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,你在每一帧显示四舍五入后的整数。

模型值与表现值

从概念上讲,可动画属性有两个值:

模型值

  • 你的代码设置的目标值
  • 当状态改变时立即更新
  • 你在视图的 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 协议允许视图通过定义哪些数据应该被插值来动画其属性。

protocol Animatable {
    associatedtype AnimatableData: VectorArithmetic

    var animatableData: AnimatableData { get set }
}

SwiftUI 为任何符合此协议的视图构建一个可动画属性。

内置的可动画视图

许多 SwiftUI 修改器符合 Animatable:

视觉效果

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

所有 Shape 类型

  • Circle、Rectangle、RoundedRectangle
  • Capsule、Ellipse、Path
  • 自定义 Shape 实现

用于多维数据的 AnimatablePair

当动画多个属性时,使用 AnimatablePair 来组合向量。

示例:scaleEffect 实现

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

    // 将两个 2D 向量组合成一个 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 是二维的(宽度、高度)
  • UnitPoint 是二维的(x、y)
  • AnimatablePair 将它们融合成一个四维向量
  • 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 需要每一帧重新计算位置。没有内置修改器可以做到这一点。


第三部分:@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("开始时间:\(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)
        }
    }
}

用例:分数动画、经验值过渡、等级进度、连击倍数

生产力应用

@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.

相关技能