Animaciones y Transiciones en SwiftUI
Guía completa sobre animaciones en SwiftUI, el nuevo macro @Animatable (iOS 26), transiciones y mejores prácticas de diseño de movimiento para el desarrollo moderno en iOS.
Requisitos previos
- iOS 17+ para PhaseAnimator/KeyframeAnimator
- iOS 26+ para el macro @Animatable
- Xcode 26+
Macro @Animatable (iOS 26 - ¡NUEVO!)
La revolución en animaciones personalizadas
iOS 26 introduce el macro @Animatable, eliminando el tedioso código repetitivo que antes se requería para animar formas y vistas personalizadas.
Antes de iOS 26 (Enfoque manual)
// FORMA ANTIGUA - Mucho código repetitivo
struct PieSlice: Shape {
var startAngle: Angle
var endAngle: Angle
// Se requería implementación manual de 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
}
}
Después de iOS 26 (Con @Animatable)
// FORMA NUEVA - Solo agrega @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
Excluye propiedades de la animación:
@Animatable
struct CustomShape: Shape {
var animatedValue: CGFloat
@AnimatableIgnored var staticConfiguration: Bool // No se anima
func path(in rect: CGRect) -> Path {
// Usa ambos valores, pero solo animatedValue se animará
}
}
Tipos compatibles para animación
El macro @Animatable maneja automáticamente:
CGFloat,Double,FloatAngleCGSize,CGPoint,CGRectUnitPointColor(interpolación de componentes)- Tipos personalizados que conformen a
VectorArithmetic
Ejemplo complejo con múltiples propiedades
@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)
}
}
// Uso
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
Uso básico
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()
}
}
}
}
}
Con tipo de animación
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
}
Manejador de finalización (iOS 17+)
withAnimation(.easeInOut(duration: 0.5)) {
showDetails = true
} completion: {
// Se llama cuando la animación termina
print("Animación finalizada")
fetchMoreData()
}
Animaciones anidadas con diferentes tiempos
Button("Animar") {
withAnimation(.spring(duration: 0.4)) {
isExpanded = true
}
withAnimation(.easeOut(duration: 0.6).delay(0.2)) {
opacity = 1.0
}
}
Tipos de animación
Animaciones integradas
// Linear - velocidad constante
.linear(duration: 0.3)
// Variantes de easing - aceleración/desaceleración
.easeIn(duration: 0.3) // Inicio lento
.easeOut(duration: 0.3) // Final lento
.easeInOut(duration: 0.3) // Ambos lentos
// Por defecto (ease in/out)
.default
Animaciones spring (modernas)
// Spring moderno con duración y rebote
.spring(duration: 0.5, bounce: 0.3)
// Valores de rebote:
// 0.0 = sin rebote (amortiguado críticamente)
// 0.5 = rebote medio
// 1.0 = rebote máximo (nunca se estabiliza)
// Parámetro extra de rebote para sobreimpulso
.spring(duration: 0.5, bounce: 0.4, blendDuration: 0.2)
Presets de spring
// Bouncy - juguetón, enérgico
.bouncy
.bouncy(duration: 0.4, extraBounce: 0.1)
// Snappy - rápido, receptivo
.snappy
.snappy(duration: 0.3, extraBounce: 0.05)
// Smooth - suave, elegante
.smooth
.smooth(duration: 0.5, extraBounce: 0.0)
Spring interactivo
// Para animaciones basadas en gestos
.interactiveSpring()
.interactiveSpring(response: 0.3, dampingFraction: 0.7)
// Ideal para gestos de arrastre
.interactiveSpring(response: 0.15, dampingFraction: 0.86, blendDuration: 0.25)
Curvas de tiempo personalizadas
// Curva de tiempo Bezier
.timingCurve(0.2, 0.8, 0.2, 1.0, duration: 0.5)
// Parámetros: (x1, y1, x2, y2)
// Inicio: (0, 0), Fin: (1, 1)
// Los puntos de control definen la forma de la curva
Modificadores de animación
// Retraso antes de comenzar
.spring().delay(0.2)
// Multiplicador de velocidad
.spring().speed(2.0) // 2x más rápido
// Repetición
.linear(duration: 1.0).repeatCount(3)
.linear(duration: 1.0).repeatForever()
// Reproducción inversa automática
.easeInOut(duration: 0.5).repeatForever(autoreverses: true)
Modificador de animación explícita
Enfoque preferido
struct ContentView: View {
@State private var scale = 1.0
var body: some View {
Circle()
.scaleEffect(scale)
// Explícita: anima solo cuando scale cambia
.animation(.spring, value: scale)
.onTapGesture {
scale = scale == 1.0 ? 1.5 : 1.0
}
}
}
Por qué lo explícito es mejor
// EVITAR: Animación implícita (anima todo)
Circle()
.animation(.spring) // Advertencia de obsoleto en iOS más recientes
// PREFERIR: Animación explícita (control preciso)
Circle()
.animation(.spring, value: specificValue)
Múltiples animaciones explícitas
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))
// Diferentes animaciones para diferentes propiedades
.animation(.bouncy, value: scale)
.animation(.easeOut(duration: 0.2), value: opacity)
.animation(.spring(duration: 1.0), value: rotation)
}
}
Transiciones
Transiciones básicas
struct ContentView: View {
@State private var showDetail = false
var body: some View {
VStack {
if showDetail {
DetailView()
.transition(.slide)
}
Button("Toggle") {
withAnimation {
showDetail.toggle()
}
}
}
}
}
Transiciones integradas
.transition(.opacity) // Fundido de entrada/salida
.transition(.scale) // Escalado desde el centro
.transition(.scale(scale: 0.5)) // Escalado desde el 50%
.transition(.slide) // Deslizamiento desde el borde principal
.transition(.move(edge: .top)) // Movimiento desde un borde específico
.transition(.push(from: .bottom)) // Empuje con reemplazo
.transition(.offset(x: 100, y: 0)) // Desplazamiento personalizado
Transiciones combinadas
// Combinar múltiples transiciones
.transition(.scale.combined(with: .opacity))
// Combinaciones en cadena
.transition(
.scale(scale: 0.8)
.combined(with: .opacity)
.combined(with: .offset(y: 20))
)
Transiciones asimétricas
// Diferentes transiciones para inserción vs. eliminación
.transition(.asymmetric(
insertion: .scale.combined(with: .opacity),
removal: .slide
))
// Patrón común: deslizar desde un lado, salir por el otro
.transition(.asymmetric(
insertion: .push(from: .trailing),
removal: .push(from: .leading)
))
Transiciones personalizadas
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)
}
}
// Uso
DetailView()
.transition(.flipFromBottom)
Phase Animator (iOS 17+)
Uso básico
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)
}
}
}
Animación activada
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("Animar") {
trigger.toggle()
}
}
}
}
Animación personalizada por fase
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+)
Animación básica con fotogramas clave
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(\value.scale) {
SpringKeyframe(1.2, duration: 0.2)
SpringKeyframe(0.9, duration: 0.15)
SpringKeyframe(1.0, duration: 0.15)
}
KeyframeTrack(\value.rotation) {
LinearKeyframe(0, duration: 0.1)
SpringKeyframe(10, duration: 0.15)
SpringKeyframe(-10, duration: 0.15)
SpringKeyframe(0, duration: 0.1)
}
KeyframeTrack(\value.yOffset) {
SpringKeyframe(-30, duration: 0.2)
SpringKeyframe(0, duration: 0.3)
}
}
.onTapGesture {
trigger.toggle()
}
}
}
Tipos de fotogramas clave
KeyframeTrack(\value) {
// Interpolación lineal
LinearKeyframe(targetValue, duration: 0.3)
// Interpolación basada en spring
SpringKeyframe(targetValue, duration: 0.3)
SpringKeyframe(targetValue, duration: 0.3, spring: .bouncy)
// Interpolación cúbica Bezier
CubicKeyframe(targetValue, duration: 0.3)
// Movimiento sin animación
MoveKeyframe(targetValue)
}
Animación compleja multipista
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
// Pista de posición X
KeyframeTrack(\value.xOffset) {
CubicKeyframe(100, duration: 0.5)
CubicKeyframe(0, duration: 0.5)
}
// Pista de posición Y
KeyframeTrack(\value.yOffset) {
CubicKeyframe(-50, duration: 0.25)
CubicKeyframe(50, duration: 0.25)
CubicKeyframe(0, duration: 0.5)
}
// Pista de escala
KeyframeTrack(\value.scale) {
SpringKeyframe(1.5, duration: 0.3, spring: .snappy)
SpringKeyframe(0.8, duration: 0.2, spring: .bouncy)
SpringKeyframe(1.0, duration: 0.3, spring: .smooth)
}
// Pista de opacidad y desenfoque
KeyframeTrack(\value.opacity) {
LinearKeyframe(0.5, duration: 0.3)
LinearKeyframe(1.0, duration: 0.7)
}
KeyframeTrack(\value.blur) {
LinearKeyframe(5, duration: 0.4)
LinearKeyframe(0, duration: 0.6)
}
}
.onTapGesture {
animating.toggle()
}
}
}
Animación de gestos
Gestos de arrastre con spring interactivo
struct DraggableView: View {
@State private var position = CGPoint.zero
@GestureState private var dragState = CGSize.zero
var body: some View {
Circle()
.fill(.blue)
.frame(width: 100, height: 100)
.offset(x: position.x + dragState.width,
y: position.y + dragState.height)
.gesture(
DragGesture()
.updating($dragState) { value, state, _ in
state = value.translation
}
.onEnded { value in
withAnimation(.interactiveSpring()) {
position.x += value.translation.width
position.y += value.translation.height
}
}
)
}
}
Gesto de pellizco para escalar
struct PinchToZoomView: View {
@State private var currentScale = 1.0
@GestureState private var gestureScale = 1.0
var body: some View {
Image(systemName: "photo")
.scaleEffect(currentScale * gestureScale)
.gesture(
MagnificationGesture()
.updating($gestureScale) { value, state, _ in
state = value
}
.onEnded { value in
withAnimation(.snappy) {
currentScale *= value
}
}
)
}
}
Gesto de rotación
struct RotationGestureView: View {
@State private var currentAngle = Angle.zero
@GestureState private var twistAngle = Angle.zero
var body: some View {
Rectangle()
.fill(.blue)
.frame(width: 200, height: 200)
.rotationEffect(currentAngle + twistAngle)
.gesture(
RotationGesture()
.updating($twistAngle) { value, state, _ in
state = value
}
.onEnded { value in
withAnimation(.interactiveSpring()) {
currentAngle += value
}
}
)
}
}
Principios de diseño de movimiento
Duraciones recomendadas
- Aparecer/desaparecer: 100-200 ms
- Transiciones entre pantallas: 300-350 ms
- Cambios de estado: 200-300 ms
- Bucles de retroalimentación: 100-150 ms
- Animaciones decorativas: 400-600 ms
Cuándo usar cada tipo de animación
| Tipo | Uso ideal | Ejemplo |
|---|---|---|
| EaseInOut | Animaciones de interfaz de usuario predecibles | Aparecer, mover, cambiar tamaño |
| Spring | Interacciones naturales con rebote | Arrastrar, soltar, tocar |
| Bouncy | Experiencias divertidas y juguetonas | Me gusta, insignias, logros |
| Snappy | Respuesta táctil rápida | Presionar botón, interruptores |
| Smooth | Transiciones elegantes y sutiles | Navegación, modales |
| InteractiveSpring | Animaciones impulsadas por gestos | Arrastrar, deslizar, pellizcar |
| Keyframe | Secuencias coreografiadas | Logotipos animados, tutoriales |
| Phase | Estados repetitivos | Latidos, notificaciones sutiles |
Mejores prácticas
- Preferir animación explícita: Usa siempre
.animation(..., value:)en lugar del modificador.animation()sin parámetros. - Elegir duraciones adecuadas: Los movimientos más cortos (100-200 ms) se sienten más rápidos y receptivos.
- Usar spring para interacciones: Los spring se sienten más naturales que las curvas de easing fijas.
- Limitar el número de propiedades animadas: Demasiadas animaciones simultáneas pueden ser abrumadoras.
- Considerar la accesibilidad: Respeta
ReduceMotiondel usuario. - Probar en dispositivos reales: Las animaciones pueden verse diferentes a cómo se ven en el simulador.
Accesibilidad: Reducir movimiento
struct AccessibleAnimation: View {
@Environment(\.accessibilityReduceMotion) var reduceMotion
@State private var isAnimating = true
var body: some View {
MovingView()
.animation(
reduceMotion ? nil : .spring,
value: isAnimating
)
}
}
Consejos para depuración
- Paso a paso: Reduce la velocidad de las animaciones en el simulador con la opción "Slow Animations" (⌘T).
- Invertir animaciones: Usa el modificador
.animation(nil, value:)para deshabilitar animaciones temporalmente durante la depuración. - Registro: Añade sentencias
printen los manejadores de finalización para rastrear la secuencia de animación. - Separar preocupaciones: Aísla las vistas animadas en componentes pequeños para facilitar la depuración.
- Previsualizar en Xcode: Usa
PreviewProvidercon diferentes estados para ver las animaciones en acción.