0
0
iOS Swiftmobile~20 mins

withAnimation in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Animated Color Toggle
This screen shows a square that changes its color smoothly when you tap a button. The color change uses withAnimation to animate the transition.
Target UI
---------------------
|                   |
|    [ Color Box ]   |
|                   |
|  [Toggle Color]    |
---------------------
Display a square box with a background color.
Add a button labeled 'Toggle Color' below the box.
When the button is tapped, the box color changes between red and blue.
Use withAnimation to animate the color change smoothly.
Starter Code
iOS Swift
import SwiftUI

struct ContentView: View {
    @State private var isRed = true

    var body: some View {
        VStack(spacing: 20) {
            Rectangle()
                .frame(width: 150, height: 150)
                .foregroundColor(isRed ? .red : .blue)

            Button("Toggle Color") {
                // TODO: Animate color change here
            }
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Task 1
Solution
iOS Swift
import SwiftUI

struct ContentView: View {
    @State private var isRed = true

    var body: some View {
        VStack(spacing: 20) {
            Rectangle()
                .frame(width: 150, height: 150)
                .foregroundColor(isRed ? .red : .blue)

            Button("Toggle Color") {
                withAnimation {
                    isRed.toggle()
                }
            }
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

We use withAnimation to wrap the state change isRed.toggle(). This tells SwiftUI to animate any view changes caused by this state update. The Rectangle changes its foregroundColor based on isRed. When toggled inside withAnimation, the color smoothly transitions between red and blue.

This is a simple way to add animation to state changes without manually defining animation modifiers.

Final Result
Completed Screen
---------------------
|                   |
|    [ Color Box ]   |
|                   |
|  [Toggle Color]    |
---------------------
Tap the 'Toggle Color' button to see the square smoothly change its color between red and blue.
Stretch Goal
Add a fade-in and fade-out animation when the color changes.
💡 Hint
Use .animation(.easeInOut(duration: 0.5), value: isRed) modifier on the Rectangle to add smooth fade transitions.