Below is a sample code that has a rectangle that is shown by default. There are two buttons to hide and show the rectangle. I want the "show" button to be shown only when the rectangle is hidden, and the "hide" button is shown only when the rectangle is shown. The transition of the rectangle state is done with an animation.
The problem is that due to the animation, if I press the "hide" button, the "show" button is immediately shown without waiting for the rectangle to be totally transitioned from opacity 1 to 0. How to have a callback at the completion of an animation so the showButtonEnabled property is set only after the animation ends?
@State var showRect = true
@State var showButtonEnabled = false
var myTestButton: some View {
HStack {
Rectangle().fill()
.opacity(showRect ? 1 : 0)
Button("Show") {
withAnimation(.linear(duration: 3)) {
showRect = true
// only do the following at the completion of the animation
showButtonEnabled = false
}
}.disabled(!showButtonEnabled)
Button("Hide") {
withAnimation(.linear(duration: 3)) {
showRect = false
// only do the following at the completion of the animation
showButtonEnabled = true
}
}.disabled(showButtonEnabled)
}
}