如何在上一个动画完成后开始动画

时间:2021-07-15 14:18:36

标签: ios swift swiftui

当我按下按钮时,我想让蓝色矩形变小,然后向右移动。

在当前代码中,将其缩小的动画和将其向右移动的动画同时发生。

在上一个动画完成后如何开始动画?

示例代码:

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()
  }
}

1 个答案:

答案 0 :(得分:1)

您可以按持续时间和延迟进行调整。

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