SwiftUI 动画与转场
面向现代 iOS 开发的 SwiftUI 动画、全新 @Animatable 宏(iOS 26)、转场及动效设计最佳实践综合指南。
先决条件
- iOS 17+ 以使用 PhaseAnimator/KeyframeAnimator
- iOS 26+ 以使用 @Animatable 宏
- Xcode 26+
@Animatable 宏(iOS 26 - 新!)
自定义动画的革命
iOS 26 引入了 @Animatable 宏,消除了以往自定义形状和视图动画所需的繁琐样板代码。
iOS 26 之前(手动方式)
// 旧方式 - 大量样板代码
struct PieSlice: Shape {
var startAngle: Angle
var endAngle: Angle
// 需要手动实现 animatableData
var animatableData: AnimatablePair<Double, Double> {
get {
AnimatablePair(startAngle.radians, endAngle.radians)
}
set {
startAngle = Angle(radians: newValue.first)
endAngle = Angle(radians: newValue.second)
}
}
func path(in rect: CGRect) -> Path {
var path = Path()
let center = CGPoint(x: rect.midX, y: rect.midY)
let radius = min(rect.width, rect.height) / 2
path.move(to: center)
path.addArc(center: center, radius: radius,
startAngle: startAngle, endAngle: endAngle,
clockwise: false)
path.closeSubpath()
return path
}
}
iOS 26 之后(使用 @Animatable)
// 新方式 - 只需添加 @Animatable
@Animatable
struct PieSlice: Shape {
var startAngle: Angle
var endAngle: Angle
func path(in rect: CGRect) -> Path {
var path = Path()
let center = CGPoint(x: rect.midX, y: rect.midY)
let radius = min(rect.width, rect.height) / 2
path.move(to: center)
path.addArc(center: center, radius: radius,
startAngle: startAngle, endAngle: endAngle,
clockwise: false)
path.closeSubpath()
return path
}
}
@AnimatableIgnored
从动画中排除属性:
@Animatable
struct CustomShape: Shape {
var animatedValue: CGFloat
@AnimatableIgnored var staticConfiguration: Bool // 不会动画
func path(in rect: CGRect) -> Path {
// 两个值都可用,但只有 animatedValue 会进行动画
}
}
支持的动画类型
@Animatable 宏自动处理:
CGFloat、Double、FloatAngleCGSize、CGPoint、CGRectUnitPointColor(组件插值)- 符合
VectorArithmetic的自定义类型
多属性复杂示例
@Animatable
struct MorphingShape: Shape {
var cornerRadius: CGFloat
var insetAmount: CGFloat
var rotation: Angle
@AnimatableIgnored var fillColor: Color
func path(in rect: CGRect) -> Path {
let insetRect = rect.insetBy(dx: insetAmount, dy: insetAmount)
var path = Path(roundedRect: insetRect, cornerRadius: cornerRadius)
let transform = CGAffineTransform(rotationAngle: rotation.radians)
return path.applying(transform)
}
}
// 使用示例
struct MorphingView: View {
@State private var isExpanded = false
var body: some View {
MorphingShape(
cornerRadius: isExpanded ? 50 : 10,
insetAmount: isExpanded ? 20 : 50,
rotation: isExpanded ? .degrees(45) : .zero,
fillColor: .blue
)
.fill(.blue)
.frame(width: 200, height: 200)
.onTapGesture {
withAnimation(.spring(duration: 0.6, bounce: 0.3)) {
isExpanded.toggle()
}
}
}
}
withAnimation
基本用法
struct ContentView: View {
@State private var isExpanded = false
var body: some View {
VStack {
Rectangle()
.frame(width: isExpanded ? 200 : 100,
height: isExpanded ? 200 : 100)
Button("Toggle") {
withAnimation {
isExpanded.toggle()
}
}
}
}
}
指定动画类型
withAnimation(.spring(duration: 0.5, bounce: 0.3)) {
isExpanded.toggle()
}
withAnimation(.easeInOut(duration: 0.3)) {
opacity = 1.0
}
withAnimation(.linear(duration: 1.0)) {
progress = 1.0
}
完成回调(iOS 17+)
withAnimation(.easeInOut(duration: 0.5)) {
showDetails = true
} completion: {
// 动画完成时调用
print("Animation finished")
fetchMoreData()
}
不同时序的嵌套动画
Button("Animate") {
withAnimation(.spring(duration: 0.4)) {
isExpanded = true
}
withAnimation(.easeOut(duration: 0.6).delay(0.2)) {
opacity = 1.0
}
}
动画类型
内置动画
// 线性 - 恒定速度
.linear(duration: 0.3)
// 缓动变体 - 加速/减速
.easeIn(duration: 0.3) // 慢速开始
.easeOut(duration: 0.3) // 慢速结束
.easeInOut(duration: 0.3) // 两头慢
// 默认(缓入缓出)
.default
弹簧动画(现代)
// 现代弹簧,带持续时间和弹力
.spring(duration: 0.5, bounce: 0.3)
// 弹力值:
// 0.0 = 无弹力(临界阻尼)
// 0.5 = 中等弹力
// 1.0 = 最大弹力(永不停止)
// 额外弹力参数用于过冲
.spring(duration: 0.5, bounce: 0.4, blendDuration: 0.2)
弹簧预设
// Bouncy - 俏皮、充满活力
.bouncy
.bouncy(duration: 0.4, extraBounce: 0.1)
// Snappy - 快速、响应式
.snappy
.snappy(duration: 0.3, extraBounce: 0.05)
// Smooth - 柔和、优雅
.smooth
.smooth(duration: 0.5, extraBounce: 0.0)
交互式弹簧
// 用于手势驱动的动画
.interactiveSpring()
.interactiveSpring(response: 0.3, dampingFraction: 0.7)
// 最适合拖拽手势
.interactiveSpring(response: 0.15, dampingFraction: 0.86, blendDuration: 0.25)
自定义时间曲线
// 贝塞尔曲线时序
.timingCurve(0.2, 0.8, 0.2, 1.0, duration: 0.5)
// 参数:(x1, y1, x2, y2)
// 开始:(0, 0),结束:(1, 1)
// 控制点定义曲线形状
动画修饰符
// 开始前延迟
.spring().delay(0.2)
// 速度倍数
.spring().speed(2.0) // 2 倍速
// 重复
.linear(duration: 1.0).repeatCount(3)
.linear(duration: 1.0).repeatForever()
// 自动反转
.easeInOut(duration: 0.5).repeatForever(autoreverses: true)
显式动画修饰符
推荐方式
struct ContentView: View {
@State private var scale = 1.0
var body: some View {
Circle()
.scaleEffect(scale)
// 显式:仅当 scale 变化时动画
.animation(.spring, value: scale)
.onTapGesture {
scale = scale == 1.0 ? 1.5 : 1.0
}
}
}
为什么显式更好
// 避免:隐式动画(将全部动画)
Circle()
.animation(.spring) // 在较新的 iOS 中已弃用
// 推荐:显式动画(精确控制)
Circle()
.animation(.spring, value: specificValue)
多个显式动画
struct MultiAnimatedView: View {
@State private var scale = 1.0
@State private var opacity = 1.0
@State private var rotation = 0.0
var body: some View {
Rectangle()
.scaleEffect(scale)
.opacity(opacity)
.rotationEffect(.degrees(rotation))
// 不同属性使用不同动画
.animation(.bouncy, value: scale)
.animation(.easeOut(duration: 0.2), value: opacity)
.animation(.spring(duration: 1.0), value: rotation)
}
}
转场
基本转场
struct ContentView: View {
@State private var showDetail = false
var body: some View {
VStack {
if showDetail {
DetailView()
.transition(.slide)
}
Button("Toggle") {
withAnimation {
showDetail.toggle()
}
}
}
}
}
内置转场
.transition(.opacity) // 淡入/淡出
.transition(.scale) // 从中心缩放
.transition(.scale(scale: 0.5)) // 从 50% 缩放
.transition(.slide) // 从领先边缘滑入
.transition(.move(edge: .top)) // 从特定边缘移动
.transition(.push(from: .bottom)) // 推送替换
.transition(.offset(x: 100, y: 0)) // 自定义偏移
组合转场
// 组合多个转场
.transition(.scale.combined(with: .opacity))
// 链式组合
.transition(
.scale(scale: 0.8)
.combined(with: .opacity)
.combined(with: .offset(y: 20))
)
不对称转场
// 插入和移除使用不同转场
.transition(.asymmetric(
insertion: .scale.combined(with: .opacity),
removal: .slide
))
// 常见模式:从一侧滑入,从另一侧滑出
.transition(.asymmetric(
insertion: .push(from: .trailing),
removal: .push(from: .leading)
))
自定义转场
extension AnyTransition {
static var flipFromBottom: AnyTransition {
.modifier(
active: FlipModifier(angle: -90),
identity: FlipModifier(angle: 0)
)
}
}
struct FlipModifier: ViewModifier {
let angle: Double
func body(content: Content) -> some View {
content
.rotation3DEffect(
.degrees(angle),
axis: (x: 1, y: 0, z: 0)
)
.opacity(angle == 0 ? 1 : 0)
}
}
// 使用示例
DetailView()
.transition(.flipFromBottom)
Phase Animator(iOS 17+)
基本用法
enum AnimationPhase: CaseIterable {
case initial
case middle
case final
var scale: CGFloat {
switch self {
case .initial: return 1.0
case .middle: return 1.2
case .final: return 1.0
}
}
var opacity: Double {
switch self {
case .initial: return 1.0
case .middle: return 0.5
case .final: return 1.0
}
}
}
struct PulsingView: View {
var body: some View {
PhaseAnimator(AnimationPhase.allCases) { phase in
Circle()
.fill(.blue)
.scaleEffect(phase.scale)
.opacity(phase.opacity)
}
}
}
触发动画
struct TriggerableAnimation: View {
@State private var trigger = false
var body: some View {
VStack {
PhaseAnimator(
AnimationPhase.allCases,
trigger: trigger
) { phase in
Star()
.scaleEffect(phase.scale)
.rotationEffect(.degrees(phase.rotation))
}
Button("Animate") {
trigger.toggle()
}
}
}
}
每个阶段自定义动画
PhaseAnimator(AnimationPhase.allCases) { phase in
ContentView(phase: phase)
} animation: { phase in
switch phase {
case .initial: .spring(duration: 0.3)
case .middle: .easeOut(duration: 0.2)
case .final: .bouncy
}
}
Keyframe Animator(iOS 17+)
基本关键帧动画
struct AnimationValues {
var scale = 1.0
var rotation = 0.0
var yOffset = 0.0
}
struct BouncingView: View {
@State private var trigger = false
var body: some View {
Circle()
.fill(.blue)
.frame(width: 100, height: 100)
.keyframeAnimator(
initialValue: AnimationValues(),
trigger: trigger
) { content, value in
content
.scaleEffect(value.scale)
.rotationEffect(.degrees(value.rotation))
.offset(y: value.yOffset)
} keyframes: { _ in
KeyframeTrack(\.scale) {
SpringKeyframe(1.2, duration: 0.2)
SpringKeyframe(0.9, duration: 0.15)
SpringKeyframe(1.0, duration: 0.15)
}
KeyframeTrack(\.rotation) {
LinearKeyframe(0, duration: 0.1)
SpringKeyframe(10, duration: 0.15)
SpringKeyframe(-10, duration: 0.15)
SpringKeyframe(0, duration: 0.1)
}
KeyframeTrack(\.yOffset) {
SpringKeyframe(-30, duration: 0.2)
SpringKeyframe(0, duration: 0.3)
}
}
.onTapGesture {
trigger.toggle()
}
}
}
关键帧类型
KeyframeTrack(\.value) {
// 线性插值
LinearKeyframe(targetValue, duration: 0.3)
// 基于弹簧的插值
SpringKeyframe(targetValue, duration: 0.3)
SpringKeyframe(targetValue, duration: 0.3, spring: .bouncy)
// 三次贝塞尔插值
CubicKeyframe(targetValue, duration: 0.3)
// 无动画移动
MoveKeyframe(targetValue)
}
复杂多轨道动画
struct ComplexAnimationValues {
var xOffset = 0.0
var yOffset = 0.0
var scale = 1.0
var opacity = 1.0
var blur = 0.0
}
struct ComplexAnimation: View {
@State private var animating = false
var body: some View {
Image(systemName: "star.fill")
.font(.system(size: 50))
.keyframeAnimator(
initialValue: ComplexAnimationValues(),
repeating: animating
) { content, value in
content
.offset(x: value.xOffset, y: value.yOffset)
.scaleEffect
…
[内容已截断,等待翻译]