0
0
iOS Swiftmobile~5 mins

withAnimation in iOS Swift

Choose your learning style9 modes available
Introduction

withAnimation helps you make changes in your app look smooth and natural by adding movement effects.

When you want a button to fade or move smoothly after tapping it.
When you change a view's size and want it to grow or shrink gently.
When showing or hiding parts of your screen with a nice transition.
When updating a list and you want new items to appear with animation.
Syntax
iOS Swift
withAnimation {
    // code that changes your view or state
}
Put the code that changes your UI inside the curly braces {}.
SwiftUI will animate the changes automatically.
Examples
This toggles a boolean to show or hide details with animation.
iOS Swift
withAnimation {
    self.showDetails.toggle()
}
This moves a view smoothly over half a second using easeInOut timing.
iOS Swift
withAnimation(.easeInOut(duration: 0.5)) {
    self.offset = 100
}
Sample App

This app shows a button that toggles a blue box on and off. The box slides in and out smoothly thanks to withAnimation.

iOS Swift
import SwiftUI

struct ContentView: View {
    @State private var isVisible = false

    var body: some View {
        VStack {
            Button("Toggle Box") {
                withAnimation {
                    isVisible.toggle()
                }
            }
            if isVisible {
                Rectangle()
                    .fill(Color.blue)
                    .frame(width: 100, height: 100)
                    .transition(.slide)
            }
        }
        .padding()
    }
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
OutputSuccess
Important Notes

withAnimation only works with SwiftUI views and state changes.

You can customize the animation style by passing parameters like .easeIn, .linear, or .spring.

Remember to put only the state changes inside withAnimation, not the UI code itself.

Summary

withAnimation makes UI changes smooth and animated.

Wrap state changes inside withAnimation { } to animate them.

You can customize animation speed and style easily.