Hi! I am trying to animate a button:
struct ButtonView: View {
@State private var isPressed = false
var label: String
let action: () -> Void
var body: some View {
Text(label)
/* There are lots of customizations here; no need to put them here */
.onTapGesture {
isPressed = true
action()
}
.scaleEffect(isPressed ? 1.25 : 1.0)
.animation(.easeInOut.repeatCount(2, autoreverses: true), value: isPressed)
}
}
This is going to create an animation that will scale out the button and then scale it back to its original size after one simple tap. In addition, it performs a custom action called action(), but that isn't really useful, I just want to be clear.
The problem is when I test this and tap the button, it runs very close to what you would expect, but with an additional and unwanted part. When I tap the button, it becomes large and then its original size and then large again, but then it jumps back with no animation to the large size again.
I believe that SwiftUI is trying to keep all of the state updated (isPressed), as it starts out false, becomes true when button is tapped, evaluates the ternary in .scaleEffect to be 1.25, which makes it larger. It then reverses this animation to make it small again... but then it must make the size larger again (1.25) because... why? I feel like I am getting confused here.
How can I make the button simply get larger and then go back to its original size? What am I misunderstanding here? Please feel free to let me know if there are any clarifications needed. I appreciate the help! :)
Hint: Realize that this isn't a SwiftUI Button type, but rather just a custom shape that I made.