SwiftUI 動畫
概觀
SwiftUI 動畫系統的完整指南,從基礎概念到進階技術。此技能涵蓋 Animatable 協議、iOS 26 的 @Animatable 巨集、動畫類型以及 Transaction 系統。
核心原則 SwiftUI 中的動畫是隨時間進行的數學插值,由 VectorArithmetic 協議驅動。理解這個基礎就能釋放 SwiftUI 宣告式動畫系統的全部潛力。
何時使用此技能
- 實作自訂的動畫視圖或形狀
- 理解為何屬性無法動畫化(Int vs 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代表什麼?
試圖動畫化 Int 時會發生什麼
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是 2 維(寬度、高度)UnitPoint是 2 維(x、y)AnimatablePair將它們融合成一個 4 維向量- 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 - Text 更新以顯示插值後的整數
效能警告
自訂 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 - 撰寫
animatableData的 getter 和 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())")
}
}
}
}
真實世界使用案例
數值動畫在各類 App 中極為常見:
金融科技 App
@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)
}
}
}
使用案例:分數動畫、經驗值過渡、等級進度、連擊倍數
生產力 App
@MainActor
@Animatable
struct TimerView: View {
var remainingSeconds: Double
…
[為翻譯而截斷]