SwiftUI Codes
Best SwiftUI Code Warehouse

Lesson 9: Animations with SwiftUI

Objective:

Learn how to create animations and transitions.

Content:

1. Basic Animations

Animating views in SwiftUI is straightforward using the withAnimation function.

Applying Animations:

@State private var scale: CGFloat = 1.0

var body: some View {
    VStack {
        Text("Tap to Animate")
            .scaleEffect(scale)
            .onTapGesture {
                withAnimation {
                    scale = scale == 1.0 ? 1.5 : 1.0
                }
            }
    }
}

Explanation:

Animating Colors:

@State private var isRed = false

var body: some View {
    VStack {
        Text("Tap to Change Color")
            .foregroundColor(isRed ? .red : .blue)
            .onTapGesture {
                withAnimation {
                    isRed.toggle()
                }
            }
    }
}

Explanation:

2. Implicit Animations

Using the .animation modifier to create implicit animations.

Using .animation Modifier:

@State private var rotation: Double = 0

var body: some View {
    Image(systemName: "arrow.right.circle")
        .rotationEffect(.degrees(rotation))
        .animation(.easeInOut(duration: 1), value: rotation)
        .onTapGesture {
            rotation += 45
        }
}

Explanation:

3. Explicit Animations

Creating custom animations with the withAnimation function.

Customizing Animations:

@State private var offset: CGFloat = 0

var body: some View {
    Text("Slide me")
        .offset(x: offset)
        .onTapGesture {
            withAnimation(.spring()) {
                offset = offset == 0 ? 100 : 0
            }
        }
}

Explanation:

Combining Multiple Animations:

@State private var scale: CGFloat = 1.0
@State private var rotation: Double = 0

var body: some View {
    VStack {
        Text("Tap to Animate")
            .scaleEffect(scale)
            .rotationEffect(.degrees(rotation))
            .onTapGesture {
                withAnimation(.easeInOut(duration: 1)) {
                    scale = scale == 1.0 ? 1.5 : 1.0
                    rotation += 45
                }
            }
    }
}

Explanation:

4. Custom Animations

Creating custom animations with the Animation struct.

Creating Custom Animations:

@State private var opacity: Double = 1.0

var body: some View {
    Text("Fade in and out")
        .opacity(opacity)
        .onAppear {
            withAnimation(Animation.easeInOut(duration: 2).repeatForever(autoreverses: true)) {
                opacity = 0.0
            }
        }
}

Explanation:

Lesson 10: Data Storage and Network Requests