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,因为:
- 没有分数中间值 —— 在 3 和 4 之间没有“3.5”
- 不连续 —— 整数是离散值
- 缩放没有意义 ——
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、RoundedRectangleCapsule、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)
工作原理
number从 0 变为 100- SwiftUI 在动画的每一帧调用
body - 每一帧都获得一个新的
number值:0 → 5 → 15 → 30 → 55 → 80 → 100 - 文本更新以显示插值后的整数
性能警告
自定义 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 之前,你必须:
- 手动符合
Animatable - 编写
animatableDatagetter 和 setter - 对多个属性使用
AnimatablePair - 手动排除不可动画的属性
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
}