SwiftUI-Animationen und -Übergänge
Umfassender Leitfaden zu SwiftUI-Animationen, dem neuen @Animatable-Makro (iOS 26), Übergängen und Best Practices im Bewegungsdesign für die moderne iOS-Entwicklung.
Voraussetzungen
- iOS 17+ für PhaseAnimator/KeyframeAnimator
- iOS 26+ für das @Animatable-Makro
- Xcode 26+
@Animatable-Makro (iOS 26 - NEU!)
Die Revolution bei benutzerdefinierten Animationen
iOS 26 führt das @Animatable-Makro ein, das den zuvor erforderlichen mühsamen Boilerplate-Code für animierte benutzerdefinierte Shapes und Views überflüssig macht.
Vor iOS 26 (Manueller Ansatz)
// ALTER WEG - Viel Boilerplate
struct PieSlice: Shape {
var startAngle: Angle
var endAngle: Angle
// Manuelle Implementierung von animatableData erforderlich
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
}
}
Nach iOS 26 (Mit @Animatable)
// NEUER WEG - Einfach @Animatable hinzufügen
@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
Eigenschaften von der Animation ausschließen:
@Animatable
struct CustomShape: Shape {
var animatedValue: CGFloat
@AnimatableIgnored var staticConfiguration: Bool // Nicht animiert
func path(in rect: CGRect) -> Path {
// Beide Werte verwenden, aber nur animatedValue wird animiert
}
}
Unterstützte Typen für die Animation
Das @Animatable-Makro verarbeitet automatisch:
CGFloat,Double,FloatAngleCGSize,CGPoint,CGRectUnitPointColor(Komponenteninterpolation)- Benutzerdefinierte Typen, die
VectorArithmeticentsprechen
Komplexes Beispiel mit mehreren Eigenschaften
@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)
}
}
// Verwendung
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
Grundlegende Verwendung
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()
}
}
}
}
}
Mit Animationstyp
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
}
Completion-Handler (iOS 17+)
withAnimation(.easeInOut(duration: 0.5)) {
showDetails = true
} completion: {
// Wird aufgerufen, wenn die Animation abgeschlossen ist
print("Animation finished")
fetchMoreData()
}
Verschachtelte Animationen mit unterschiedlichen Zeitabläufen
Button("Animate") {
withAnimation(.spring(duration: 0.4)) {
isExpanded = true
}
withAnimation(.easeOut(duration: 0.6).delay(0.2)) {
opacity = 1.0
}
}
Animationstypen
Integrierte Animationen
// Linear - konstante Geschwindigkeit
.linear(duration: 0.3)
// Ease-Varianten - Beschleunigung/Verzögerung
.easeIn(duration: 0.3) // Langsamer Start
.easeOut(duration: 0.3) // Langsames Ende
.easeInOut(duration: 0.3) // Beides langsam
// Standard (ease in/out)
.default
Federanimationen (Modern)
// Moderne Feder mit Dauer und Bounce
.spring(duration: 0.5, bounce: 0.3)
// Bounce-Werte:
// 0.0 = kein Bounce (kritisch gedämpft)
// 0.5 = mittlerer Bounce
// 1.0 = maximaler Bounce (pendelt nie aus)
// Zusätzlicher Bounce-Parameter für Überschwingen
.spring(duration: 0.5, bounce: 0.4, blendDuration: 0.2)
Feder-Voreinstellungen
// Bouncy - verspielt, energiegeladen
.bouncy
.bouncy(duration: 0.4, extraBounce: 0.1)
// Snappy - schnell, reaktionsschnell
.snappy
.snappy(duration: 0.3, extraBounce: 0.05)
// Smooth - sanft, elegant
.smooth
.smooth(duration: 0.5, extraBounce: 0.0)
Interaktive Feder
// Für gestengetriebene Animationen
.interactiveSpring()
.interactiveSpring(response: 0.3, dampingFraction: 0.7)
// Am besten für Drag-Gesten
.interactiveSpring(response: 0.15, dampingFraction: 0.86, blendDuration: 0.25)
Benutzerdefinierte Zeitsteuerungskurven
// Bezier-Kurvenzeitsteuerung
.timingCurve(0.2, 0.8, 0.2, 1.0, duration: 0.5)
// Parameter: (x1, y1, x2, y2)
// Start: (0, 0), Ende: (1, 1)
// Kontrollpunkte definieren die Kurvenform
Animationsmodifikatoren
// Verzögerung vor dem Start
.spring().delay(0.2)
// Geschwindigkeitsmultiplikator
.spring().speed(2.0) // 2x schneller
// Wiederholung
.linear(duration: 1.0).repeatCount(3)
.linear(duration: 1.0).repeatForever()
// Automatische Umkehrung
.easeInOut(duration: 0.5).repeatForever(autoreverses: true)
Expliziter Animationsmodifikator
Bevorzugter Ansatz
struct ContentView: View {
@State private var scale = 1.0
var body: some View {
Circle()
.scaleEffect(scale)
// Explizit: nur animieren, wenn sich scale ändert
.animation(.spring, value: scale)
.onTapGesture {
scale = scale == 1.0 ? 1.5 : 1.0
}
}
}
Warum explizit besser ist
// VERMEIDEN: Implizite Animation (animiert alles)
Circle()
.animation(.spring) // Veraltete Warnung in neueren iOS
// BEVORZUGEN: Explizite Animation (präzise Steuerung)
Circle()
.animation(.spring, value: specificValue)
Mehrere explizite Animationen
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))
// Unterschiedliche Animationen für verschiedene Eigenschaften
.animation(.bouncy, value: scale)
.animation(.easeOut(duration: 0.2), value: opacity)
.animation(.spring(duration: 1.0), value: rotation)
}
}
Übergänge
Grundlegende Übergänge
struct ContentView: View {
@State private var showDetail = false
var body: some View {
VStack {
if showDetail {
DetailView()
.transition(.slide)
}
Button("Toggle") {
withAnimation {
showDetail.toggle()
}
}
}
}
}
Integrierte Übergänge
.transition(.opacity) // Ein-/Ausblenden
.transition(.scale) // Von der Mitte skalieren
.transition(.scale(scale: 0.5)) // Von 50 % skalieren
.transition(.slide) // Von der Vorderseite schieben
.transition(.move(edge: .top)) // Von einer bestimmten Kante bewegen
.transition(.push(from: .bottom)) // Mit Ersetzung schieben
.transition(.offset(x: 100, y: 0)) // Benutzerdefinierter Versatz
Kombinierte Übergänge
// Mehrere Übergänge kombinieren
.transition(.scale.combined(with: .opacity))
// Kombinationen verketten
.transition(
.scale(scale: 0.8)
.combined(with: .opacity)
.combined(with: .offset(y: 20))
)
Asymmetrische Übergänge
// Unterschiedliche Übergänge für Einfügen vs. Entfernen
.transition(.asymmetric(
insertion: .scale.combined(with: .opacity),
removal: .slide
))
// Häufiges Muster: von einer Seite hereinschieben, zur anderen hinaus
.transition(.asymmetric(
insertion: .push(from: .trailing),
removal: .push(from: .leading)
))
Benutzerdefinierte Übergänge
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)
}
}
// Verwendung
DetailView()
.transition(.flipFromBottom)
Phase Animator (iOS 17+)
Grundlegende Verwendung
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)
}
}
}
Ausgelöste Animation
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()
}
}
}
}
Benutzerdefinierte Animation pro Phase
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+)
Grundlegende Keyframe-Animation
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()
}
}
}
Keyframe-Typen
KeyframeTrack(\.value) {
// Lineare Interpolation
LinearKeyframe(targetValue, duration: 0.3)
// Federbasierte Interpolation
SpringKeyframe(targetValue, duration: 0.3)
SpringKeyframe(targetValue, duration: 0.3, spring: .bouncy)
// Kubische Bezier-Interpolation
CubicKeyframe(targetValue, duration: 0.3)
// Bewegung ohne Animation
MoveKeyframe(targetValue)
}
Komplexe Multi-Track-Animation
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)
SpringKeyframe(-50, duration: 0.6)
SpringKeyframe(0, duration: 0.4)
}
KeyframeTrack(\.yOffset) {
SpringKeyframe(-30, duration: 0.3)
CubicKeyframe(30, duration: 0.5)
SpringKeyframe(0, duration: 0.4)
}
KeyframeTrack(\.scale) {
CubicKeyframe(1.5, duration: 0.3)
LinearKeyframe(0.8, duration: 0.2)
SpringKeyframe(1.0, duration: 0.3, spring: .bouncy)
}
KeyframeTrack(\.opacity) {
LinearKeyframe(1.0, duration: 0.2)
SpringKeyframe(0.5, duration: 0.3)
LinearKeyframe(1.0, duration: 0.5)
}
KeyframeTrack(\.blur) {
CubicKeyframe(5, duration: 0.4)
SpringKeyframe(0, duration: 0.6)
}
}
.onTapGesture {
animating.toggle()
}
}
}
Animationsprotokolle (Animation Protocols)
Equatable und Hashable
// Notwendig für @State und explizite Animationen
struct AnimationState: Equatable {
var scale: CGFloat
var rotation: Double
var opacity: Double
}
Animations-Utilities
Allgemeine Animation als Funktionsreferenz
struct AnimatedView: View {
@State private var animate = false
var body: some View {
Circle()
.fill(.blue)
.overlay(
Circle()
.stroke(Color.blue, lineWidth: 2)
.scaleEffect(animate ? 1.5 : 1.0)
.opacity(animate ? 0.0 : 1.0)
)
.onAppear {
withAnimation(.easeOut(duration: 1.0).repeatForever(autoreverses: false)) {
animate = true
}
}
}
}
Animationshilfen (Helpers)
Sonstige Hilfsfunktionen
// Aktion mit Verzögerung ausführen
withAnimation(
.default
.delay(0.3)
) {
showView = true
}
Performance-Tipps
- Verwende
.drawingGroup()für komplexe Animationen - Bevorzuge explizite Animationen (
animation(_, value:)) vor impliziten - Nutze
PhaseAnimatorundKeyframeAnimatorfür komplexe, mehrphasige Animationen - Vermeide übermäßige State-Updates innerhalb von
withAnimation - Verwende
AnimatablePairfür benutzerdefinierte Animationen komplexer Typen
Beispielprojekt: Interaktiver Bewegungspfad (Interactive Motion Path)
@Animatable
struct MotionPathView: View {
@State private var phase = 0.0
let animation = Animation
.spring(duration: 5.0, bounce: 0.5)
.repeatForever(autoreverses: false)
var body: some View {
VStack {
Circle()
.fill(.blue)
.frame(width: 100, height: 100)
.overlay(
Circle()
.stroke(Color.blue, lineWidth: 2)
.scaleEffect(1.0 + 0.5 * sin(phase))
.opacity(0.5)
)
.offset(
x: 50 * cos(phase * 2),
y: 50 * sin(phase * 3)
)
.onAppear {
withAnimation(animation) {
phase = .pi * 2
}
}
}
.frame(width: 200, height: 200)
}
}