SwiftUI 애니메이션
개요
SwiftUI의 애니메이션 시스템에 대한 포괄적인 가이드로, 기본 개념부터 고급 기술까지 다룹니다. 이 스킬은 Animatable 프로토콜, iOS 26의 @Animatable 매크로, 애니메이션 유형, 그리고 Transaction 시스템을 포함합니다.
핵심 원칙 SwiftUI의 애니메이션은 시간에 따른 수학적 보간(interpolation)이며, VectorArithmetic 프로토콜에 의해 구동됩니다. 이 기반을 이해하면 SwiftUI의 선언적 애니메이션 시스템의 모든 기능을 활용할 수 있습니다.
이 스킬을 사용해야 할 때
- 커스텀 애니메이션 뷰 또는 셰이프 구현
- 특정 속성이 애니메이션되지 않는 이유 이해 (Int vs Float/Double)
- 스프링과 타이밍 곡선 애니메이션 중 선택
- @Animatable 매크로 사용 (iOS 26+)
- Animatable 프로토콜에 뷰 적합시키기
- 애니메이션 병합 동작 디버깅
- 애니메이션 성능 최적화
- 다단계 또는 복잡한 애니메이션 생성
- 모델 값과 프레젠테이션 값의 이해
- 커스텀 애니메이션 알고리즘 구현
시스템 요구 사항
iOS 13+ Animatable 프로토콜용
iOS 17+ 기본 스프링 애니메이션, 범위 제한 애니메이션용
iOS 26+ @Animatable 매크로용
파트 1: 애니메이션 이해하기
보간(Interpolation)이란?
애니메이션은 시작 상태와 종료 상태 사이의 중간 값을 생성하는 과정입니다.
예: 불투명도 애니메이션
.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
// 0 값
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을 보간하고, 각 프레임에서 반올림된 정수를 표시합니다.
모델 값 vs 프레젠테이션 값
애니메이션 가능 속성은 개념적으로 두 가지 값을 가집니다:
모델 값
- 코드에서 설정한 목표 값
- 상태 변경 시 즉시 업데이트됨
- 뷰의 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()— 그림자 속성 애니메이션
모든 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 - 텍스트가 보간된 정수를 표시하도록 업데이트
성능 경고
커스텀 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을 애니메이션하려면 매 프레임마다 위치를 다시 계산해야 합니다. 내장 수정자로는 불가능합니다.
파트 3: @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 타입 — Color, String, Bool
예시
@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)
}
}
}
사용 사례: 점수 애니메이션, XP 전환, 레벨 진행, 콤보 배수
생산성 앱
@MainActor
@Animatable
struct TimerView: View {
var remainingSeconds: Double
var body: some View {
Text(timerInterval: ...)
.font(.system(size: 50, weight: .light, design: .monospaced))
}
}
사용 사례: 카운트다운 타이머, 진행 표시기, 작업 완료율, 예산 추적기
파트 4: 애니메이션 생성하기
기본 애니메이션 구문
애니메이션 수정자
// 명시적 애니메이션 (기존)
withAnimation(.spring) {
scale = 1.5
}
// 값 기반 암시적 애니메이션 (iOS 17+)
.animation(.spring, value: scale)
// 범위 제한 애니메이션 (iOS 17+)
.animation(.spring) {
self.scale
self.opacity
}
// 전역 암시적 애니메이션 (레거시, 권장하지 않음)
.animation(.spring)
**iOS 17의 animation(_:value:)**가 선호되는 방식입니다. value 매개변수는 변경을 감시할 속성을 지정합니다. SwiftUI는 해당 속성이 변경될 때만 body를 호출하여 뷰를 애니메이션합니다.
struct AnimationScopeExample: View {
@State private var scale: CGFloat = 1.0
@State private var opacity: Double = 1.0
var body: some View {
Circle()
.scaleEffect(scale)
.opacity(opacity)
.animation(.spring) {
$0.scaleEffect(scale)
}
.animation(.easeInOut) {
$0.opacity(opacity)
}
}
}
애니메이션 유형
스프링 애니메이션
// 부드러운 스프링 (물리 기반)
Animation.spring
Animation.spring(duration: 0.5, bounce: 0.3)
Animation.snappy
Animation.smooth
Animation.bouncy
// 레거시 스프링
Animation.interpolatingSpring(mass: 1.0, stiffness: 100, damping: 10, initialVelocity: 0)
Animation.spring(response: 0.55, dampingFraction: 0.825, blendDuration: 0)
특징
- 물리 시뮬레이션 기반
- 자연스러운 느낌과 반응성
- 과도한 튕김 없음
- iOS 17+에서 기본값
타이밍 곡선
// 베지어 곡선 (입방형)
Animation.easeInOut
Animation.easeIn
Animation.easeOut
Animation.linear
Animation.timingCurve(0.2, 0.8, 0.2, 1.0, duration: 0.5)
특징
- 미리 정의된 곡선 모양
- 예측 가능하고 일관된 동작
- 긴 지속 시간에 적합
- 스프링보다 덜 자연스러움
기타 애니메이션 유형
// 충격 (iOS 17+)
Animation.interactiveSpring
// 펄스 효과 (iOS 17+)
Animation.pulse
// 키프레임 (iOS 17+)
Animation.keyframe {
KeyframeTrack(\.scale) {
LinearKeyframe(1.0, duration: 0.2)
SpringKeyframe(1.5, duration: 0.4)
CubicKeyframe(1.0, duration: 0.4)
}
}
애니메이션 수정자
// 애니메이션 지연
Animation.spring.delay(0.5)
// 애니메이션 속도 (재생 속도)
Animation.spring.speed(2)
// 애니메이션 반복
Animation.spring.repeatCount(3, autoreverses: true)
Animation.spring.repeatForever(autoreverses: true)
// 완료 콜백
withAnimation(.spring) {
// 애니메이션할 속성
} completion: {
// 애니메이션 완료 후 실행
}
키프레임 애니메이션 (iOS 17+)
// 키프레임 트랙
Animation.keyframe {
KeyframeTrack(\.scale) {
LinearKeyframe(1.0, duration: 0.2)
SpringKeyframe(1.5, duration: 0.4)
CubicKeyframe(1.0, duration: 0.4)
}
KeyframeTrack(\.rotation) {
LinearKeyframe(.degrees(0), duration: 0.2)
SpringKeyframe(.degrees(360), duration: 0.4)
CubicKeyframe(.degrees(360), duration: 0.4)
}
}
// 사용 예
struct KeyframeAnimationExample: View {
@State private var scale: CGFloat = 1.0
var body: some View {
Circle()
.scaleEffect(scale)
.onTapGesture {
withAnimation(.keyframe {
KeyframeTrack(\.scale) {
LinearKeyframe(1.0, duration: 0.2)
SpringKeyframe(1.5, duration: 0.4)
CubicKeyframe(1.0, duration: 0.4)
}
}) {
scale = 1.0
}
}
}
}
파트 5: Transaction 시스템
개요
Transaction은 애니메이션의 메타데이터를 전달하는 SwiftUI의 메커니즘입니다. 애니메이션을 시작할 때, Transaction은 시스템 전체에 흐르며 모든 수정자가 애니메이션 동작을 조정할 수 있게 합니다.
수동 Transaction 설정
// 애니메이션과 함께 Transaction 생성
var transaction = Transaction(animation: .spring)
transaction.disablesAnimations = false
transaction.isContinuous = false
// Transaction 적용
withTransaction(transaction) {
// 애니메이션할 속성
}
// Transaction 수정자
.transaction { transaction in
transaction.animation = transaction.animation?.delay(0.5)
transaction.disablesAnimations = true
}
Transaction 수정자 체이닝
struct TransactionChainExample: View {
@State private var scale: CGFloat = 1.0
var body: some View {
Circle()
.scaleEffect(scale)
.transaction { transaction in
// 외부 애니메이션 재정의
transaction.animation = .spring.delay(1.0)
}
.onTapGesture {
withAnimation(.easeInOut) {
scale = 1.5
}
}
}
}
Transaction disablesAnimations
// 애니메이션 비활성화
withAnimation(.spring) {
// 이 속성은 애니메이션됨
scale = 1.5
// 하지만 이 속성은 Transaction 수정자에 의해 비활성화됨
withTransaction(Transaction(disablesAnimations: true)) {
opacity = 0.5
}
}
파트 6: 모범 사례 및 문제 해결
모범 사례
1. @Animatable 매크로 사용 (iOS 26+)
가능하면 @Animatable 매크로를 사용하여 수동 Animatable 적합성의 상용구를 제거하세요.
// 권장
@MainActor
@Animatable
struct MyView: View {
var scale: CGFloat
var opacity: Double
var body: some View {
// ...
}
}
// 권장하지 않음 (iOS 26+에서)
struct MyView: View, Animatable {
var scale: CGFloat
var opacity: Double
var animatableData: AnimatablePair<CGFloat, Double> {
get { AnimatablePair(scale, opacity) }
set { scale = newValue.first; opacity = newValue.second }
}
var body: some View {
// ...
}
}
2. 성능을 위해 내장 수정자 선호
// 권장 (성능 우수)
Circle()
.scaleEffect(scale)
.opacity(opacity)
.animation(.spring, value: scale)
.animation(.easeInOut, value: opacity)
// 필요할 때만 커스텀 Animatable 사용
@Animatable
struct CustomShape: Shape {
var progress: Double
func path(in rect: CGRect) -> Path {
// 커스텀 드로잉 경로
}
}
3. 상태 변경에 대한 애니메이션 범위 지정
// 권장
extension MyView {
var animatedScale: some View {
scaleEffect(scale)
.animation(.spring, value: scale)
}
}
// 권장하지 않음
extension MyView {
var animatedScale: some View {
scaleEffect(scale)
.animation(.spring) // 범위 없음
}
}
일반적인 문제 해결
"속성이 애니메이션되지 않습니다"
문제: 보간을 사용하는 애니메이션이 예상대로 작동하지 않습니다. 해결책:
- 속성이 VectorArithmetic에 적합한지 확인 (Float/Double, Int 아님)
- .animation 수정자에 올바른 value 매개변수가 있는지 확인
- Transaction 수정자가 애니메이션을 비활성화하지 않는지 확인
- -- animatableData가 올바르게 설정되었는지 확인
"애니메이션이 너무 느립니다"
문제: 커스텀 Animatable 뷰가 성능 문제를 일으킵니다. 해결책:
- Instruments로 프로파일링하여 병목 지점 식별
- 내장 수정자로 대체 가능한지 확인
- 애니메이션 중복 계산 최소화
- 가능하면 @AnimatableIgnored 사용
"애니메이션이 올바르게 완료되지 않습니다"
문제: 완료 핸들러가 예상대로 실행되지 않습니다. 해결책:
- withAnimation 완료 핸들러가 외부 상태 변경 후 실행되는지 확인
- 중첩된 withAnimation 블록 확인
- Transaction 수정자가 애니메이션을 수정하지 않는지 확인
학습 보충 자료
공식 문서
WWDC 세션
- iOS 26: SwiftUI 애니메이션 심층 분석
- iOS 17: 키프레임 및 스프링 애니메이션
- iOS 15: 애니메이션 성능 최적화
추천 도구
- Instruments: SwiftUI 애니메이션 프로파일링
- SwiftUI Previews: 실시간 애니메이션 디버깅