SwiftUI 애니메이션 및 전환
SwiftUI 애니메이션, 새로운 @Animatable 매크로(iOS 26), 전환 및 최신 iOS 개발을 위한 모션 디자인 모범 사례에 대한 종합 가이드입니다.
사전 요구 사항
- PhaseAnimator/KeyframeAnimator: iOS 17+
- @Animatable 매크로: iOS 26+
- Xcode 26+
@Animatable 매크로 (iOS 26 - 신규!)
커스텀 애니메이션의 혁신
iOS 26은 @Animatable 매크로를 도입하여, 커스텀 모양과 뷰에 애니메이션을 적용하는 데 이전에 필요했던 지루한 보일러플레이트를 제거했습니다.
iOS 26 이전 (수동 접근 방식)
// OLD WAY - 많은 보일러플레이트
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 사용)
// NEW WAY - @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 - 일정한 속도
.linear(duration: 0.3)
// Ease 변형 - 가속/감속
.easeIn(duration: 0.3) // 느린 시작
.easeOut(duration: 0.3) // 느린 끝
.easeInOut(duration: 0.3) // 양쪽 모두 느림
// 기본 (ease in/out)
.default
스프링 애니메이션 (최신)
// 지속 시간과 바운스가 있는 최신 스프링
.spring(duration: 0.5, bounce: 0.3)
// Bounce 값:
// 0.0 = 바운스 없음 (임계 감쇠)
// 0.5 = 중간 바운스
// 1.0 = 최대 바운스 (결코 안정되지 않음)
// 오버슈트를 위한 추가 bounce 매개변수
.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(value.scale)
.opacity(value.opacity)
.blur(radius: value.blur)
} keyframes: { _ in
KeyframeTrack(\.xOffset) {
SpringKeyframe(50, duration: 0.4, spring: .bouncy)
SpringKeyframe(0, duration: 0.4, spring: .snappy)
}
KeyframeTrack(\.scale) {
CubicKeyframe(1.5, duration: 0.4)
CubicKeyframe(0.8, duration: 0.2)
CubicKeyframe(1.2, duration: 0.2)
CubicKeyframe(1.0, duration: 0.2)
}
KeyframeTrack(\.opacity) {
LinearKeyframe(0.5, duration: 0.2)
LinearKeyframe(1.0, duration: 0.6)
}
}
}
}
모션 디자인 모범 사례
성능 고려 사항
// GPU 가속 프로퍼티에 애니메이션 적용 (높은 성능)
.opacity
.scaleEffect
.offset
.rotationEffect
.blur(radius:)
// 레이아웃 다시 계산을 유발하는 프로퍼티 피하기 (낮은 성능)
.frame
.padding
.position
접근성을 위한 모션 감소
struct MotionAwareView: View {
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var isAnimating = false
var body: some View {
Circle()
.scaleEffect(isAnimating ? 1.2 : 1.0)
.animation(
reduceMotion ? nil : .spring(bounce: 0.5),
value: isAnimating
)
}
}
애니메이션 타이밍 팁
- UI 피드백: 0.1~0.2초 (사용자 상호작용에 즉각적인 느낌)
- 뷰 전환: 0.3~0.4초 (섹션 간 자연스러운 이동)
- 표현적 애니메이션: 0.5~1.0초 (더 복잡한 모션)
- 로딩 인디케이터: 1.0~2.0초 (반복 패턴)
일반적인 패턴
애니메이션 가능한 뷰 래퍼
struct AnimatableView<Content: View>: View {
let content: Content
let animation: Animation
@Binding var isAnimating: Bool
var body: some View {
content
.animation(animation, value: isAnimating)
}
}
체인 애니메이션
struct ChainedAnimation: View {
@State private var step1 = false
@State private var step2 = false
@State private var step3 = false
var body: some View {
VStack {
Circle()
.scaleEffect(step1 ? 1.2 : 1.0)
.animation(.spring, value: step1)
Circle()
.scaleEffect(step2 ? 1.2 : 1.0)
.animation(.spring.delay(0.2), value: step2)
Circle()
.scaleEffect(step3 ? 1.2 : 1.0)
.animation(.spring.delay(0.4), value: step3)
}
.onTapGesture {
step1 = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
step2 = true
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
step3 = true
}
}
}
}
요약
SwiftUI 애니메이션은 상태 기반 선언적 모델을 사용합니다:
| 개념 | 목적 | iOS 버전 |
|---|---|---|
@Animatable | Shape/View 프로퍼티를 자동으로 애니메이션 가능하게 함 | 26+ |
withAnimation | 암시적 애니메이션 블록 | 15+ |
.animation(_, value:) | 명시적 애니메이션 수정자 | 17+ |
| 전환 | View 표시/숨기기를 위한 애니메이션 | 15+ |
| PhaseAnimator | 일련의 단계를 통한 순환 애니메이션 | 17+ |
| KeyframeAnimator | 정밀한 다중 트랙 키프레임 애니메이션 | 17+ |