Use when implementing SwiftUI animations, understanding VectorArithmetic, using @Animatable macro, zoom transitions, UIKit/AppKit animation bridging, choosing between spring and timing curve animations, or debugging animation behavior - comprehensive animation reference from iOS 13 through iOS 26
/plugin marketplace add CharlesWiltgen/Axiom/plugin install axiom@axiom-marketplaceThis skill inherits all available tools. When active, it can use any tool Claude has access to.
Comprehensive guide to SwiftUI's animation system, from foundational concepts to advanced techniques. This skill covers the Animatable protocol, the iOS 26 @Animatable macro, animation types, and the Transaction system.
Core principle Animation in SwiftUI is mathematical interpolation over time, powered by the VectorArithmetic protocol. Understanding this foundation unlocks the full power of SwiftUI's declarative animation system.
Animation is the process of generating intermediate values between a start and end state.
.opacity(0) → .opacity(1)
While this animation runs, SwiftUI computes intermediate values:
0.0 → 0.02 → 0.05 → 0.1 → 0.25 → 0.4 → 0.6 → 0.8 → 1.0
How values are distributed
SwiftUI requires animated data to conform to VectorArithmetic, which provides:
protocol VectorArithmetic {
// Compute difference between two values
static func - (lhs: Self, rhs: Self) -> Self
// Scale values
static func * (lhs: Self, rhs: Double) -> Self
// Add values
static func + (lhs: Self, rhs: Self) -> Self
// Zero value
static var zero: Self { get }
}
Built-in conforming types
CGFloat, Double, Float, AngleCGPoint, CGSizeCGRectKey insight Vector arithmetic abstracts over the dimensionality of animated data. SwiftUI can animate all these types with a single generic implementation.
Int does not conform to VectorArithmetic because:
struct CounterView: View {
@State private var count: Int = 0
var body: some View {
Text("\(count)")
.animation(.spring, value: count)
}
}
Result: SwiftUI simply replaces the old text with the new one. No interpolation occurs.
struct AnimatedCounterView: View {
@State private var count: Float = 0
var body: some View {
Text("\(Int(count))")
.animation(.spring, value: count)
}
}
Result: SwiftUI interpolates 0.0 → ... → 100.0, and you display the rounded integer at each frame.
Animatable attributes conceptually have two values:
Example
.scaleEffect(selected ? 1.5 : 1.0)
When selected becomes true:
1.51.0 → 1.1 → 1.2 → 1.3 → 1.4 → 1.5 over timeThe Animatable protocol allows views to animate their properties by defining which data should be interpolated.
protocol Animatable {
associatedtype AnimatableData: VectorArithmetic
var animatableData: AnimatableData { get set }
}
SwiftUI builds an animatable attribute for any view conforming to this protocol.
Many SwiftUI modifiers conform to Animatable:
.scaleEffect() — Animates scale transform.rotationEffect() — Animates rotation.offset() — Animates position offset.opacity() — Animates transparency.blur() — Animates blur radius.shadow() — Animates shadow propertiesCircle, Rectangle, RoundedRectangleCapsule, Ellipse, PathShape implementationsWhen animating multiple properties, use AnimatablePair to combine vectors.
struct ScaleEffectModifier: ViewModifier, Animatable {
var scale: CGSize
var anchor: UnitPoint
// Combine two 2D vectors into one 4D vector
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)
}
}
How it works
CGSize is 2-dimensional (width, height)UnitPoint is 2-dimensional (x, y)AnimatablePair fuses them into a 4-dimensional vectorstruct AnimatableNumberView: View, Animatable {
var number: Double
var animatableData: Double {
get { number }
set { number = newValue }
}
var body: some View {
Text("\(Int(number))")
.font(.largeTitle)
}
}
// Usage
AnimatableNumberView(number: value)
.animation(.spring, value: value)
How it works
number changes from 0 to 100body for every frame of the animationnumber value: 0 → 5 → 15 → 30 → 55 → 80 → 100Custom Animatable conformance can be expensive.
When you conform a view to Animatable:
body for every frame of the animationBuilt-in animatable effects (like .scaleEffect(), .opacity()) are much more efficient:
Guideline
// This is expensive but necessary for animating along a circular path
@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)
}
}
}
Why necessary: Animating offsetAngle requires recalculating positions every frame. No built-in modifier can do this.
The @Animatable macro eliminates the boilerplate of manually conforming to the Animatable protocol.
Before iOS 26, you had to:
AnimatableanimatableData getter and setterAnimatablePair for multiple propertiesiOS 26+, you just add @Animatable:
@MainActor
@Animatable
struct MyView: View {
var scale: CGFloat
var opacity: Double
var body: some View {
// ...
}
}
The macro automatically:
Animatable conformanceanimatableData from VectorArithmetic-conforming propertiesAnimatablePairstruct HikingRouteShape: Shape {
var startPoint: CGPoint
var endPoint: CGPoint
var elevation: Double
var drawingDirection: Bool // Don't want to animate this
// Tedious manual animatableData declaration
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 {
// Drawing code
}
}
@Animatable
struct HikingRouteShape: Shape {
var startPoint: CGPoint
var endPoint: CGPoint
var elevation: Double
@AnimatableIgnored
var drawingDirection: Bool // Excluded from animation
func path(in rect: CGRect) -> Path {
// Drawing code
}
}
Lines of code: 20 → 12 (40% reduction)
Use @AnimatableIgnored to exclude properties from animation.
@MainActor
@Animatable
struct ProgressView: View {
var progress: Double // Animated
var totalItems: Int // Animated (if Float, not if Int)
@AnimatableIgnored
var title: String // Not animated
@AnimatableIgnored
var startTime: Date // Not animated
@AnimatableIgnored
var debugEnabled: Bool // Not animated
var body: some View {
VStack {
Text(title)
ProgressBar(value: progress)
if debugEnabled {
Text("Started: \(startTime.formatted())")
}
}
}
}
Numeric animations are extremely common across app categories:
@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)
}
}
}
Use case: Animate stock price changes, portfolio value, account balance transitions
@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)
}
}
}
Use case: Heart rate indicators, step counters, calorie calculations, distance traveled
@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)
}
}
}
Use case: Score animations, XP transitions, level progress, combo multipliers
@MainActor
@Animatable
struct TimerView: View {
var remainingSeconds: Double
var body: some View {
let minutes = Int(remainingSeconds) / 60
let seconds = Int(remainingSeconds) % 60
Text(String(format: "%02d:%02d", minutes, seconds))
.font(.system(.largeTitle, design: .monospaced))
}
}
Use case: Progress bars, countdown timers, percentage indicators, task completion metrics
struct ContentView: View {
@State private var stockPrice: Double = 142.50
var body: some View {
VStack(spacing: 20) {
StockPriceView(price: stockPrice, changePercent: 0.025)
.animation(.spring(duration: 0.8), value: stockPrice)
Button("Simulate Price Change") {
stockPrice = Double.random(in: 130...160)
}
.buttonStyle(.borderedProminent)
}
.padding()
}
}
@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)
.fontWeight(.semibold)
Text("\(changePercent > 0 ? "+" : "")\(changePercent, format: .percent.precision(.fractionLength(2)))")
.font(.subheadline)
.foregroundColor(changePercent > 0 ? .green : .red)
}
}
}
Result: Smooth, natural animation of stock price changes that feels professional and polished.
Timing curve animations use bezier curves to control the speed of animation over time.
.animation(.linear) // Constant speed
.animation(.easeIn) // Starts slow, ends fast
.animation(.easeOut) // Starts fast, ends slow
.animation(.easeInOut) // Slow start and end, fast middle
let customCurve = UnitCurve(
startControlPoint: CGPoint(x: 0.2, y: 0),
endControlPoint: CGPoint(x: 0.8, y: 1)
)
.animation(.timingCurve(customCurve, duration: 0.5))
All timing curve animations accept an optional duration:
.animation(.easeInOut(duration: 0.3))
.animation(.linear(duration: 1.0))
Default: 0.35 seconds
Spring animations use physics simulation to create natural, organic motion.
.animation(.smooth) // No bounce (default since iOS 17)
.animation(.snappy) // Small amount of bounce
.animation(.bouncy) // Larger amount of bounce
.animation(.spring(duration: 0.6, bounce: 0.3))
Parameters
duration — Perceived animation durationbounce — Amount of bounce (0 = no bounce, 1 = very bouncy)Much more intuitive than traditional spring parameters (mass, stiffness, damping).
Modify base animations to create complex effects.
.animation(.spring.delay(0.5))
Waits 0.5 seconds before starting the animation.
.animation(.easeInOut.repeatCount(3, autoreverses: true))
.animation(.linear.repeatForever(autoreverses: false))
Repeats the animation multiple times or infinitely.
.animation(.spring.speed(2.0)) // 2x faster
.animation(.spring.speed(0.5)) // 2x slower
Multiplies the animation speed.
Before iOS 17
withAnimation {
// Used timing curve by default
}
iOS 17+
withAnimation {
// Uses .smooth spring by default
}
Why the change: Spring animations feel more natural and preserve velocity when interrupted.
Recommendation: Embrace springs. They make your UI feel more responsive and polished.
The most common way to trigger an animation.
Button("Scale Up") {
withAnimation(.spring) {
scale = 1.5
}
}
How it works
withAnimation opens a transactionwithAnimation(.spring(duration: 0.6, bounce: 0.4)) {
isExpanded.toggle()
}
withAnimation(nil) {
// Changes happen immediately, no animation
resetState()
}
Apply animations to specific values within a view.
Circle()
.fill(isActive ? .blue : .gray)
.animation(.spring, value: isActive)
How it works: Animation only applies when isActive changes. Other state changes won't trigger this animation.
Circle()
.scaleEffect(scale)
.animation(.bouncy, value: scale)
.opacity(opacity)
.animation(.easeInOut, value: opacity)
Different animations for different properties.
Narrowly scope animations to specific animatable attributes.
struct AvatarView: View {
var selected: Bool
var body: some View {
Image("avatar")
.scaleEffect(selected ? 1.5 : 1.0)
.animation(.spring, value: selected)
// ⚠️ If image also changes when selected changes,
// image transition gets animated too (accidental)
}
}
struct AvatarView: View {
var selected: Bool
var body: some View {
Image("avatar")
.animation(.spring, value: selected) {
$0.scaleEffect(selected ? 1.5 : 1.0)
}
// ✅ Only scaleEffect animates, image transition doesn't
}
}
How it works
Define your own transaction values to propagate custom context.
struct AvatarTappedKey: TransactionKey {
static let defaultValue: Bool = false
}
extension Transaction {
var avatarTapped: Bool {
get { self[AvatarTappedKey.self] }
set { self[AvatarTappedKey.self] = newValue }
}
}
var transaction = Transaction()
transaction.avatarTapped = true
withTransaction(transaction) {
isSelected.toggle()
}
.transaction { transaction in
if transaction.avatarTapped {
transaction.animation = .bouncy
} else {
transaction.animation = .smooth
}
}
Use case: Apply different animations based on how the state change was triggered (tap vs programmatic).
Implement your own animation algorithms.
protocol CustomAnimation {
// Calculate current value
func animate<V: VectorArithmetic>(
value: V,
time: TimeInterval,
context: inout AnimationContext<V>
) -> V?
// Optional: Should this animation merge with previous?
func shouldMerge<V>(previous: Animation, value: V, time: TimeInterval, context: inout AnimationContext<V>) -> Bool
// Optional: Current velocity
func velocity<V: VectorArithmetic>(
value: V,
time: TimeInterval,
context: AnimationContext<V>
) -> V?
}
struct LinearAnimation: CustomAnimation {
let duration: TimeInterval
func animate<V: VectorArithmetic>(
value: V, // Delta vector: target - current
time: TimeInterval, // Elapsed time since animation started
context: inout AnimationContext<V>
) -> V? {
// Animation is done when time exceeds duration
if time >= duration {
return nil
}
// Calculate linear progress (0.0 to 1.0)
let progress = time / duration
// Scale the delta vector by progress
// This returns how much to move FROM current position
// NOT the final target position
return value.scaled(by: progress)
}
}
Critical understanding: The value parameter is the delta vector (target - current), not the target value itself.
Example in practice:
10.0100.0animate(): 90.0 (target - current)return value.scaled(by: 0.5) → returns 45.010.0 + 45.0 = 55.0 (halfway to target) ✅Common mistake:
// ❌ WRONG: Treating value as the target
let progress = time / duration
return value.scaled(by: progress) // This assumes value is delta
// ❌ WRONG: Trying to interpolate manually
let target = value // No! value is already the delta
return current + (target - current) * progress // Incorrect
// ✅ CORRECT: Scale the delta
return value.scaled(by: progress) // SwiftUI handles the addition
What happens when a new animation starts before the previous one finishes?
func shouldMerge(...) -> Bool {
return false // Default implementation
}
Behavior: Both animations run together, results are combined additively.
Example
func shouldMerge(...) -> Bool {
return true // Springs override this
}
Behavior: New animation incorporates state of previous animation, preserving velocity.
Example
Why springs feel more natural: They preserve momentum when interrupted.
iOS 18 introduces the zoom transition, where a tapped cell morphs into the incoming view. This transition is continuously interactive—users can grab and drag the view during or after the transition begins.
Key benefit In parts of your app where you transition from a large cell, zoom transitions increase visual continuity by keeping the same UI elements on screen across the transition.
Two steps to adopt zoom transitions:
NavigationLink {
BraceletEditor(bracelet)
.navigationTransition(.zoom(sourceID: bracelet.id, in: namespace))
} label: {
BraceletPreview(bracelet)
}
BraceletPreview(bracelet)
.matchedTransitionSource(id: bracelet.id, in: namespace)
struct BraceletListView: View {
@Namespace private var braceletList
let bracelets: [Bracelet]
var body: some View {
NavigationStack {
ScrollView {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 150))]) {
ForEach(bracelets) { bracelet in
NavigationLink {
BraceletEditor(bracelet: bracelet)
.navigationTransition(
.zoom(sourceID: bracelet.id, in: braceletList)
)
} label: {
BraceletPreview(bracelet: bracelet)
}
.matchedTransitionSource(id: bracelet.id, in: braceletList)
}
}
}
}
}
}
func showEditor(for bracelet: Bracelet) {
let braceletEditor = BraceletEditorViewController(bracelet: bracelet)
// Step 1: Specify zoom transition on the pushed view controller
braceletEditor.preferredTransition = .zoom { context in
// Step 2: Return the source view
let editor = context.zoomedViewController as! BraceletEditorViewController
return self.cell(for: editor.bracelet)
}
navigationController?.pushViewController(braceletEditor, animated: true)
}
Critical detail The closure is called on both zoom in and zoom out. Capture a stable identifier (like the model object), not a view directly—the source view may get reused in a collection view.
If the editor's content can change (e.g., swiping between items), use the context to retrieve the current item:
braceletEditor.preferredTransition = .zoom { context in
let editor = context.zoomedViewController as! BraceletEditorViewController
// Use current bracelet, not the one captured at push time
return self.cell(for: editor.bracelet)
}
Zoom transitions work with fullScreenCover and sheet in both SwiftUI and UIKit:
.fullScreenCover(item: $selectedBracelet) { bracelet in
BraceletEditor(bracelet: bracelet)
.navigationTransition(.zoom(sourceID: bracelet.id, in: namespace))
}
Use the configuration closure to style the source during transition:
.matchedTransitionSource(id: bracelet.id, in: namespace) { source in
source
.cornerRadius(8.0)
.shadow(radius: 4)
}
Modifiers applied here are smoothly interpolated during the zoom transition.
Key insight Push transitions cannot be cancelled. When interrupted, they convert to pop transitions.
Disappeared → [viewWillAppear] → Appearing → [viewIsAppearing] → [viewDidAppear] → Appeared
Appearing → Appeared → Disappearing → ...
The push completes immediately, then the pop begins. The view controller always reaches the Appeared state—callbacks complete their full cycle for consistency.
// ❌ DON'T: Block actions during transitions
func handleTap() {
guard !isTransitioning else { return } // Don't do this
pushViewController(...)
}
// ✅ DO: Always allow the action
func handleTap() {
pushViewController(...) // System handles overlapping transitions
}
Guidelines
viewDidAppear or viewDidDisappeariOS 18 enables using SwiftUI Animation types to animate UIKit and AppKit views. This provides access to the full suite of SwiftUI animations, including custom animations.
@MainActor static func animate(
_ animation: Animation,
changes: () -> Void,
completion: (() -> Void)? = nil
)
// Old way: Describe spring in parameters
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.5) {
bead.center = endOfBracelet
}
// New way: Use SwiftUI Animation type
UIView.animate(.spring(duration: 0.5)) {
bead.center = endOfBracelet
}
All SwiftUI animations work with UIKit views:
// Timing curves
UIView.animate(.linear(duration: 0.3)) { ... }
UIView.animate(.easeIn(duration: 0.3)) { ... }
UIView.animate(.easeOut(duration: 0.3)) { ... }
UIView.animate(.easeInOut(duration: 0.3)) { ... }
// Springs
UIView.animate(.spring) { ... }
UIView.animate(.spring(duration: 0.6, bounce: 0.3)) { ... }
UIView.animate(.smooth) { ... }
UIView.animate(.snappy) { ... }
UIView.animate(.bouncy) { ... }
// Repeating
UIView.animate(.linear(duration: 1.3).repeatForever()) { ... }
// Custom animations
UIView.animate(myCustomAnimation) { ... }
Important architectural difference:
| Old UIKit API | New SwiftUI Animation API |
|---|---|
Generates a CAAnimation | No CAAnimation generated |
| Animation added to layer | Animates presentation values directly |
Animation in layer's animations dict | Presentation values in presentation layer |
Both approaches reflect values in the presentation layer, but the mechanism differs.
class BeadViewController: UIViewController {
private var animatingView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
animatingView = UIImageView(image: UIImage(systemName: "circle.fill"))
animatingView.tintColor = .systemPink
animatingView.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
view.addSubview(animatingView)
animatingView.center = view.center
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
startAnimating()
}
private func startAnimating() {
let animation = Animation
.linear(duration: 1.3)
.repeatForever()
UIView.animate(animation) { [weak self] in
self?.animatingView.transform = CGAffineTransform(scaleX: 2, y: 2)
}
}
}
When wrapping UIKit views in SwiftUI, animations don't automatically bridge:
struct BeadBoxWrapper: UIViewRepresentable {
@Binding var isOpen: Bool
func updateUIView(_ box: BeadBox, context: Context) {
// ❌ Animation on binding doesn't affect UIKit
box.lid.center.y = isOpen ? -100 : 100
}
}
// Usage
BeadBoxWrapper(isOpen: $isOpen)
.animation(.spring, value: isOpen) // No effect on UIKit view
Use context.animate() to bridge SwiftUI animations:
struct BeadBoxWrapper: UIViewRepresentable {
@Binding var isOpen: Bool
func makeUIView(context: Context) -> BeadBox {
BeadBox()
}
func updateUIView(_ box: BeadBox, context: Context) {
// ✅ Bridges animation from Transaction to UIKit
context.animate {
box.lid.center.y = isOpen ? -100 : 100
}
}
}
Transactioncontext.animate() reads the Transaction's animationcontext.animate {
// Changes here
} completion: {
// Called when animation completes
// If not animated, called immediately inline
}
Works whether animated or not — safe to always use this pattern.
A single animation running across SwiftUI Views and UIViews runs perfectly in sync. This enables seamless mixed hierarchies.
Traditional UIKit gesture animations require manual velocity calculation:
// Old way: Manual velocity computation
func handlePan(_ gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .changed:
bead.center = gesture.location(in: view)
case .ended:
let velocity = gesture.velocity(in: view)
let distance = endOfBracelet.distance(to: bead.center)
// 😫 Convert to unit velocity manually
let unitVelocity = CGVector(
dx: velocity.x / distance,
dy: velocity.y / distance
)
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: unitVelocity.length) {
bead.center = endOfBracelet
}
}
}
SwiftUI animations automatically preserve velocity through animation merging:
// New way: Automatic velocity preservation
func handlePan(_ gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .changed:
// Interactive spring during drag
UIView.animate(.interactiveSpring) {
bead.center = gesture.location(in: view)
}
case .ended:
// Final spring uses velocity from interactiveSprings
UIView.animate(.spring) {
bead.center = endOfBracelet
}
}
}
[Drag starts]
↓
[.changed] → interactiveSpring animation (retargets previous)
↓
[.changed] → interactiveSpring animation (retargets previous)
↓
[.changed] → interactiveSpring animation (retargets previous)
↓
[.ended] → .spring animation inherits velocity from interactiveSprings
↓
[Smooth deceleration to final position]
No velocity calculation needed — SwiftUI handles it automatically.
struct DraggableBead: View {
@State private var position: CGPoint = .zero
@State private var isDragging = false
var body: some View {
Circle()
.position(position)
.gesture(
DragGesture()
.onChanged { value in
withAnimation(.interactiveSpring) {
position = value.location
}
}
.onEnded { value in
withAnimation(.spring) {
position = targetPosition
}
}
)
}
}
Continuous velocity creates natural, physical-feeling interactions:
Built-in animatable attributes run efficiently:
.scaleEffect(scale)
.opacity(opacity)
.rotationEffect(angle)
Benefits
bodyCustom Animatable conformance runs on main thread:
@MainActor
@Animatable
struct MyView: View {
var value: Double
var animatableData: Double {
get { value }
set { value = newValue }
}
var body: some View {
// Called every frame! (main thread)
}
}
Performance tip: Profile with Instruments if you have many custom animatable views.
SwiftUI animates the difference between values, not the values themselves.
// User taps, scale changes from 1.0 to 1.5
.scaleEffect(isSelected ? 1.5 : 1.0)
What SwiftUI actually animates
Why this matters
Symptom: Property changes but doesn't animate.
@State private var count: Int = 0 // ❌ Int doesn't animate
// Solution
@State private var count: Double = 0 // ✅ Double animates
Text("\(Int(count))") // Display as Int
// ❌ No animation specified
Text("\(value)")
// ✅ Add animation
Text("\(value)")
.animation(.spring, value: value)
struct ProgressView: View {
@State private var progress: Double = 0
@State private var title: String = "Loading"
var body: some View {
VStack {
Text(title)
ProgressBar(value: progress)
}
.animation(.spring, value: title) // ❌ Animates when title changes, not progress
}
}
// Solution
.animation(.spring, value: progress) // ✅
If you have a custom view with animatable properties:
// ❌ Missing Animatable conformance
struct MyView: View {
var value: Double
var body: some View { ... }
}
// ✅ Add @Animatable macro (iOS 26+)
@MainActor
@Animatable
struct MyView: View {
var value: Double
var body: some View { ... }
}
// ✅ OR manual conformance (iOS 13+)
struct MyView: View, Animatable {
var value: Double
var animatableData: Double {
get { value }
set { value = newValue }
}
var body: some View { ... }
}
Symptom: Animation is choppy or drops frames.
@MainActor
@Animatable
struct ExpensiveView: View {
var value: Double
var animatableData: Double {
get { value }
set { value = newValue }
}
var body: some View {
// ❌ Called every frame!
let heavyComputation = performExpensiveWork(value)
return Text("\(heavyComputation)")
}
}
Solution: Use built-in effects instead
struct OptimizedView: View {
@State private var value: Double = 0
var body: some View {
Text("\(computeOnce(value))")
.opacity(value) // ✅ Built-in effect, off-main-thread
}
}
Profile with Instruments to identify bottlenecks.
Symptom: Animation behavior changes when interrupted.
Cause: Spring animations merge by default, preserving velocity from the previous animation.
Solution: Use a timing curve animation if you don't want merging behavior:
// ❌ Spring merges with previous animation
withAnimation(.spring) {
scale = 1.0
}
// ✅ Timing curve starts fresh (additive, no merge)
withAnimation(.easeInOut(duration: 0.5)) {
scale = 1.0
}
See Animation Merging Behavior section above for detailed explanation of merge vs additive animations.
WWDC: 2023-10156, 2023-10157, 2023-10158, 2024-10145, 2025-256
Docs: /swiftui/animatable, /swiftui/animation, /swiftui/vectorarithmetic, /swiftui/transaction, /swiftui/view/navigationtransition(:), /swiftui/view/matchedtransitionsource(id:in:configuration:), /uikit/uiview/animate(:changes:completion:)
Skills: axiom-swiftui-26-ref, axiom-swiftui-nav-ref, axiom-swiftui-performance, axiom-swiftui-debugging
Last Updated Based on WWDC 2023/10156-10158, WWDC 2024/10145, WWDC 2025/256 Version iOS 13+ (Animatable), iOS 17+ (scoped animations), iOS 18+ (zoom transitions, UIKit bridging), iOS 26+ (@Animatable)
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.