代码之家  ›  专栏  ›  技术社区  ›  shingo.nakanishi

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

  •  0
  • shingo.nakanishi  · 技术社区  · 5 年前

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

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

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

    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 回复  |  直到 5 年前
        1
  •  1
  •   Raja Kishan    5 年前

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

    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