shingo.nakanishi
shingo.nakanishi

Reputation: 2837

How to start an animation after the previous one has finished

When I press the button, I want to make the blue rectangle smaller and then move it to the right.

In the current code, the animation to make it smaller and the animation to move it to the right happen at the same time.

How do you start an animation after the previous one has finished?

sample code:

import SwiftUI

struct ContentView: View {
  @State private var scale: CGFloat = 1
  @State private var offsetX: CGFloat = 1
  
  var body: some View {
    VStack {
      Button(
        action: {
          withAnimation {
            scale = scale - 0.1
          }
          withAnimation {
            offsetX = offsetX + 25
          }
        },
        label: {
          Text("Tap Me")
        }
      )
      RectangleView().scaleEffect(
        scale
      )
      .offset(
        x: offsetX,
        y: 0
      )
    }
  }
}

struct RectangleView: View {
  var body: some View {
    Rectangle().fill(
      Color.blue
    )
    .frame(
      width: 200,
      height: 150
    )
  }
}

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

Upvotes: 0

Views: 56

Answers (1)

Raja Kishan
Raja Kishan

Reputation: 19044

You can adjust by duration and delay.

struct ContentView: View {
    @State private var scale: CGFloat = 1
    @State private var offsetX: CGFloat = 1
    
    var body: some View {
        VStack {
            Button(
                action: {
                    withAnimation(.linear(duration: 0.2)) { //<-- Here
                        scale = scale - 0.1
                    }
                    withAnimation(Animation.default.delay(0.2)) { //<-- Here
                        offsetX = offsetX + 25
                    }
                    
                },
                label: {
                    Text("Tap Me")
                }
            )
            RectangleView().scaleEffect(
                scale
            )
            .offset(
                x: offsetX,
                y: 0
            )
        }
    }
}

enter image description here

Upvotes: 1

Related Questions