4

I am trying to chain two animations in SwiftUI. However, the first animation does not animate when pressing the button. I found this approach of chaining animations here: Chaining animations in SwiftUI

struct FancyButtonViewModel: View { @State var movementY:CGFloat = 0 var body: some View { VStack{ Text("😇") .offset(y: movementY) Button("Press Me"){ withAnimation(Animation.easeOut(duration: 0.5)) { movementY = -150 } withAnimation(Animation.easeIn(duration: 3).delay(0.5)) { movementY = 0 } } } } } 
1
  • The emoji should first move within 0.5 seconds 150 pixels north and after that within 3 seconds back to its origin. The first animation is not smooth, it directly jumps to 150 pixels (no animation there). Commented Nov 21, 2020 at 22:44

1 Answer 1

4

You can fix this by using DispatchQueue and async after a while. So remove the delay from the animation and pass it to the DispatchQueue.

struct ContentView: View { @State var movementY: CGFloat = 0 var body: some View { VStack{ Text("😇") .offset(y: movementY) Button("Press Me"){ withAnimation(Animation.easeOut(duration: 0.5)) { movementY = -150 } DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { withAnimation(Animation.easeIn(duration: 3)) { movementY = 0 } } } } } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.