I want to make the button move up and down (with animation) on click but when I click it, It moves only up and then I have to click it again to move the button back. How can I make the button move up and then automatically back to its first position without clicking it again?
@State var isAnimated: Bool = false;
var body: some View {
VStack {
Button(action: {
withAnimation(Animation.default.repeatCount(1, autoreverses: true)) {
isAnimated.toggle()
}
}) {
Text("Text")
.foregroundColor(Color(red: 0.998, green: 0.369, blue: 0.369))
.font(.system(size: 33))
}
.frame(width: 100, height: 100)
.background(Color(.blue))
.offset(y: isAnimated ? 100 : 0)
}
.padding()
}
}`
This seems like a trivial problem with a simple solution but the way SwiftUI handles the animation and the repeatForever(_:autoreverses:) method makes it more effortful. The `repeatCount a parameter requires an odd number to prevent the strange “jumps”, and using either of the values 1 and 3 result in no fix.
The solution I found was to create two separate animations, one delayed after the other.
withAnimation {
isAnimated = true
withAnimation(.default.delay(0.4)) { // play with delay to see what feels right
isAnimated = false
}
}